NYCPHP Meetup

NYPHP.org

[nycphp-talk] __get __set methods..

Christopher Hendry chendry at gmail.com
Wed Apr 20 11:38:24 EDT 2005


I'm still kinda wondering tho - as nifty as all this is - on the
engine level how much overhead is involved here.  In the example
below, if instantiating with an array of data, we have an 'is_array' a
'foreach' then a call to magic '__set', which then does an 'isset' ...

Hmm...certainly there are times when you want your objects to act on
unknown data, but for the most part, and certainly this Runner example
- shouldn't we bind the data to the object and thus predefine the
properties?

On 4/19/05, Daniel Krook <krook at us.ibm.com> wrote:
> Actually, the key to the whole thing  (also from Adam's book, pp 261-263)
> is to define what values are acceptable as properties in the constructor.
> In this example only valOne and valTwo can be set and get:
> 
> class Runner {
> 
>         private $data;
> 
>         public function __construct($runner = null) {
>                 $this->data     = array(
>                         'valOne' => 0,
>                         'valTwo' => ''
>                 );
>                 if (is_array($runner)) {
>                         foreach ($runner as $field => $value) {
>                                 $this->$field = $value;
>                         }
>                 }
>         }
> 
>         public function __set($property, $value) {
>                 if (isset($this->data[$property])) {
>                         $this->data[$property] = $value;
>                 }
>         }
> 
>         public function __get($property) {
>                 if (isset($this->data[$property])) {
>                         return $this->data[$property];
>                 } else {
>                         return false;
>                 }
>         }
> }
>



More information about the talk mailing list