PHP __get magic method unexpected behaviour -


i have following classes.

class book {      protected $name;     protected $cost;     protected $description;      public function __construct(){         $this->name = 'the x';         $this->cost = 19.95;         $this->description = 'something x';     }      public function __get($variable){         return $this->$variable;     } } 

class readerabstract {      protected $_book;      public function __construct(){         if(null == $this->_book){             $this->_book = new book();         }     }      public function __get($variable){         $method = 'get'.ucwords($variable);         if(method_exists($this, $method)){             return $this->$method();         }         return $this->getbook()->__get($variable);     }      public function getbook(){         return $this->_book;     }  } 

class reader extends readerabstract {      public function getcost(){         return round($this->cost, 2);         //return round($this->getbook()->cost, 2); doing works expected     }  } 

now if this.

$reader = new reader(); echo $reader->name; //this should work echo '<br />'; echo $reader->cost; //this should go infinite loop echo '<br />'; echo $reader->description; //this should work 

the code above works fine expect statement echo $reader->cost; throws "undefined property: reader::$cost" error.

my questions here are:

  1. why can't access property $cost?

  2. shouldn't call $cost property trigger infinite loop? i.e. each time call $reader->cost call gets redirected getcost() method , inside getcost() method if call $this->cost shouldn't call method getcost() creating infinite loop?

thanks help.

the problem __get method not reentrant, when access $reader->cost called first time , call reader::getcost(), $this->cost forces php recursive call __get denied.

i don't know if it's bug or feature. read this page php manual , search 'recursi' further reading.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -