我有以下课程。
class Book {
protected $name;
protected $cost;
protected $description;
public function __construct(){
$this->name = 'The X';
$this->cost = 19.95;
$this->description = 'Something about 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 this works as expected
}
}
现在,如果我这样做。
$reader = new Reader();
echo $reader->name; //This should work
echo '<br />';
echo $reader->cost; //This should go into an infinite loop
echo '<br />';
echo $reader->description; //This should work
上面的代码可以正常工作,但语句echo $reader->cost;
会抛出"Undefined property: Reader::$cost"
错误。
我的问题是:
为什么我无法访问该物业
$cost
?对 $cost 属性的调用不应该触发无限循环吗?即每次我调用 $reader->cost 时,调用都会重定向到 getCost() 方法,如果我调用 $this->cost ,它会在 getCost() 方法内部不应该调用方法 getCost() 创建无限循环吗?
谢谢你的帮助。