NYCPHP Meetup

NYPHP.org

[nycphp-talk] __get __set methods..

Christopher Hendry chendry at gmail.com
Tue Apr 19 22:01:26 EDT 2005


__set and __get are magic methods that are called only when the
properties are not defined in the class, thus, this works:

  class Runner  {

       public function __get($property){
               return $this->$property;
       }

       public function __set($property, $value){
               $this->$property = $value;
       }

  }

though I believe this is better (pg 39 - Upgrading to PHP5 - how's
that for a plug Adam?):

  class Runner  {
       private $data;

       public function __get($property){
               if (isset($this->data[$property])){
                 return $this->data[$property];
               } else return false;
       }

       public function __set($property, $value){
               $this->data[$property] = $value;
       }
}


Why?  My guess is because you're able to define your data as private
via the array...however, I would be interested to know here from
someone who knows for certain.


On 4/19/05, Alex C <alexchan.1976 at gmail.com> wrote:
> I am trying to use __set and __get magic methods to access private
> properties of a class. However , I keep on getting this error. I am
> using PHP 5.03..
> 
> Fatal error: Cannot access private property Runner::$programName
> 
> I am not sure what I am doing wrong..  thanks in advance
> 
> my class looks as follows.
> ---
> 
>   class Runner  {
>         private $programName;
>         private $programDate;
>         private $raceNumber;
>         private $runnerNumber;
> 
>         private $scratchedStatus;
> 
>         public function __get($property){
>                 return $this->$property;
>         }
> 
>         public function __set($property, $value){
>                 $this->$property = $value;
>         }
> }
> _______________________________________________
> New York PHP Talk Mailing List
> AMP Technology
> Supporting Apache, MySQL and PHP
> http://lists.nyphp.org/mailman/listinfo/talk
> http://www.nyphp.org
> 


-- 

"When you do things right, people won't be sure you've done anything at all."



More information about the talk mailing list