SitePoint Sponsor

User Tag List

Results 1 to 9 of 9
  1. #1
    SitePoint Zealot Steveiwonder's Avatar
    Join Date
    Nov 2008
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Getting a property from another class.

    Hello guys & gals,

    How can i access another classes property? If i'm doing it all wrong then let me know. Here below is a simple example of what im trying to do, all i'm missing is the getter method to retrieve the other classes property.

    Code PHP:
     
    class object1{
       public $property1 = "1";
    }
     
    class getObject1_Property1 {
      public function someGetterMethod(){
       //need code here:(
      }
    }
     
     
    $aClass = new object1();
    $getValue = new getObject1_Property1();
    echo $getValue->someGetterFunctions();// This is the function i need to create to access the propert of $aClass

    i seem to have no idea :/
    //Steve
    Follow the dream, don't chase the competition.

  2. #2
    SitePoint Addict joaquin_win's Avatar
    Join Date
    Jul 2005
    Location
    Venezuela
    Posts
    224
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That would break Object Oriented encapsulation. Maybe getObject1_Property1 can have an object1 property inside and the you can return object->property using someGetterFunctions

  3. #3
    SitePoint Evangelist
    Join Date
    Jun 2006
    Location
    Wigan, Lancashire. UK
    Posts
    523
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code PHP:
     
    class object1{
       public $property1 = "1";
    }
     
    class getObject1_Property1 {
      private $object1_Class;
      public function someGetterMethod(){
       return $this->object1_Class->$property1;
      }
      function __construct($object1_Class) {
         $this->object1_Class = $object1_Class;
      }
    }
     
     
    $aClass = new object1();
    $getValue = new getObject1_Property1($aClass);
    echo $getValue->someGetterFunctions();// This is the function i need to create to access the propert of $aClass
    ---
    Development Projects:
    PHPExcel
    PHPPowerPoint

  4. #4
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Whilst I question your need to do this, maybe this will help.

    PHP Code:
    <?php
    class Bacon
    {
        public 
    $sType 'Smoked Back';
    }

    class 
    Breakfast
    {
        protected 
    $oBacon;
        
        public function 
    __construct(Bacon $oBacon)
        {
            
    $this->oBacon $oBacon;
        }
        
        public function 
    getBaconType()
        {
            return 
    $this->oBacon->sType;
        }
    }

    $oBreakfast = new Breakfast(new Bacon());
    echo 
    $oBreakfast->getBaconType(); #Smoked Back
    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  5. #5
    SitePoint Zealot Steveiwonder's Avatar
    Join Date
    Nov 2008
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by SilverBulletUK View Post
    Whilst I question your need to do this, maybe this will help.
    Let me explain, maybe i'm just doing it wrong. Here is my real code.

    class_lib.php
    Code PHP:
    class newUser {
      private $fname;
      private $lname;
      private $age;
      private $sex;
      private $email;
     
      public $errors = array();
     
      function __construct($fname, $lname, $age, $sex, $email){
     
        $this->fname = $fname;
        $this->lname = $lname;
        $this->age = $age;
        $this->sex = $sex;
        $this->email = $email;
      }
     
      public function addUser(){
        if($this->validateUser()){// If passes validation.
     
          $addUser = "INSERT
                      INTO
                      users
                      (fname, lname, age, sex, email)
                      VALUES
                      ('{$this->fname}','{$this->lname}','{$this->age}','{$this->sex}','{$this->email}')";
          $result = mysql_query($addUser);
     
          if($result){
            return true;
          }else{
            $this->errors[] = "Unable to add user. Please try again.";
          }
        }
      }  
     
      private function validateUser(){
        $passed = true;
        if($this->fname == '' || strpos($this->fname, " ") == true){
          $this->errors[] = 'First Name Invalid. Cannot be empty or contain spaces.';
          $passed = false;
        }
     
        if($this->lname == '' || strpos($this->lname, " ") == true){
          $this->errors[] = 'Last Name Invalid. Cannot be empty or contain spaces.';
          $passed = false;
        }
     
        //check if email address is unused.
        $query = "SELECT email FROM users WHERE email = '{$this->email}'";
        $result = mysql_query($query);
        if(mysql_num_rows($result)!='0'){
          $this->errors[] = "Email Invalid. This email address is already being used.";
          $passed = false;
        }
     
        return $passed;
     
      }
     
      public function getErrors(){
        return $this->errors; // pass the errors back to the script for output.
      }
     
     
    }

    index.php

    Code PHP:
    <?php
     
    mysql_connect("localhost", "root", "password01");
    mysql_select_db("oop");
     
    $new_user = new newUser('Steven', 'Yates', '20', 'M','[example]@hotmail.com');
    if($new_user->addUser()){
      echo 'Added to database';
    }else{//output the errors generate by "new_user";
      //**********************************
      foreach($new_user->getErrors() as $error){
        echo $error."<br>";
      }
      //**********************************
    }
    ?>

    The foreach loop above, the reason i want to access another classes property is i'm trying to make a error class that is more generic. Instead of having to add the error method "getErrors" & public error property "errors[]" to each class like i would if i continued with the above code. So how I thought it was meant to be acheive is like so... each class that can generate errors still has
    Code PHP:
    public $errors = array();

    but in place of the foreach loop highlighted above it would be something
    like.
    Code PHP:
    $errors = new errorClass();// this class holding the method
                              // which gets the property from the other class
    $getErrors = $errors->getErrors($new_user->errors);
     
    foreach($getErrors as $error){
      echo $error."<br>";
    }
    That is atleast how i saw it should work in my head?

    I guess there is an easier, simpler way to achieve this can you shed some light? If something above doesnt make sense then let me try and explain.

    p.s. the code above is very basic and only uses this to teach myself OOP.

    Thanks

    //Steve
    Last edited by Stevie D; Sep 5, 2012 at 14:20. Reason: Personal email address redacted
    Follow the dream, don't chase the competition.

  6. #6
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    If my rather slack knowledge of OOP stacks up, because you want many objects to have the same way of getting errors, you should create a common interface for it.

    This allows you to make sure other objects HAVE to follow the contract defined, this allows you to pass any object implementing the interface around without worrying if the object has the methods needed.

    You'll have to forgive my lame naming, IErrorable indeed!

    PHP Code:
    <?php
    interface IErrorable
    {
        public function 
    getErrors();
    }

    class 
    User implements IErrorable
    {
        protected 
    $aErrors = array();
        
        public function 
    getErrors()
        {
            return 
    $this->aErrors;
        }
    }

    class 
    Database implements IErrorable
    {
        protected 
    $aErrors = array();
        
        public function 
    getErrors()
        {
            return 
    $this->aErrors;
        }
    }

    class 
    ErrorPrinter
    {
        public static function 
    Render(IErrorable $oObject)
        {
            foreach(
    $oObject->getErrors() as $sError)
            {
                
    printf(
                    
    '<p class="systemError"><strong>Error:</strong>%s</p>',
                    
    $sError
                
    );
            }
        }
    }

    class 
    ErrorLogger
    {
        public static function 
    Log(IErrorable $oObject)
        {
            foreach(
    $oObject->getErrors() as $sError)
            {
                
    file_put_contents('log.txt'$sError "\r\n"FILE_APPEND);
            }
        }
    }

    $oUser = new User();
    $oDatatbase = new Database();
    /* do stuff */
    ErrorLogger::Log($oUser);
    ErrorPrinter::Render($oUser);
    ErrorLogger::Log($oDatatbase);
    ErrorPrinter::Render($oDatatbase);
    ?>
    I'll await a telling off from some of the guru's on this!

    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  7. #7
    SitePoint Evangelist
    Join Date
    Jun 2006
    Location
    Wigan, Lancashire. UK
    Posts
    523
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well the errors class probably doesn't need to be instantiated: you could create it as a series of static attributes/methods.

    PHP Code:
    class errors {
      private 
    $_errors = array();

      public static function 
    addError($errMsg) {
        
    self::$_errors[] = $errMsg;
      } 
    // function addError()

      
    public static function getErrors() {
         return 
    self::$_errors;
      } 
    // function getErrors()

      
    public static function errorCount() {
         return 
    count(self::$_errors);
      } 
    // function errorCount()
    // class errors

    class newUser {
       public function 
    __construct($data=null) {
          if (
    is_null($data)) {
             
    errors::addError('Missing user data');
             return 
    False;
          }
          return 
    True;
       }  
    //  function __construct
    }  //  class newUser

    $newUser = new newUser();
    if (
    errors::errorCount() > 0) {
       foreach(
    errors::getErrors() as $error) {
          echo 
    $error.'<br />';
       }

    ---
    Development Projects:
    PHPExcel
    PHPPowerPoint

  8. #8
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,151
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by Mark Baker
    Well the errors class probably doesn't need to be instantiated: you could create it as a series of static attributes/methods.
    Using a interface is more appropriate because it decouples the error from the log object.

  9. #9
    SitePoint Zealot Steveiwonder's Avatar
    Join Date
    Nov 2008
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for all your replies, i have yet to learn about interfaces - can someonepoint me in the right direction?

    Can a few people explain how they handle errors uses classes, is it using the same method as above or something similar. A few ideas would be good.
    Follow the dream, don't chase the competition.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •