我不知道我在哪裏做錯了。有人可以告訴我嗎?__get和__set代碼的問題
<?php
class something
{
public $attr1;
private $attr2;
public function __get($name)
{
return $this->$name;
}
public function __set($name,$value)
{
$this->$name = $value." added something more";
}
}
$a = new something();
$a->$attr1 = "attr1";
$a->$attr2 = "attr2";
echo $a->$attr1; //what I would expect is attr1 as output
echo $a->$attr2; //what I would expect is attr2 added something more as output
?>
雖然這兩個魔術方法都得心應手保持記住很多人(包括我在內),不推薦的使用它們,因爲它們[打破對象封裝](http://en.wikipedia.org/wiki/Encapsulation_object-oriented_programming)。 – stefgosselin 2011-05-29 21:10:11
請參閱[這篇文章的正確使用示例](http://stackoverflow.com/questions/3634748/php-zend-say-avoid-magic-methods)尊重封裝。 – stefgosselin 2011-05-29 21:17:32