我是php world的新手。我正在尝试理解 __ set()魔术方法在php中是如何工作的。我使用 __ set()创建一个新属性 方法。我有一个if语句来检查属性是否已经存在。如果不存在,那么它会创建属性并为其赋值。我在检查两个属性。它们是 $ newProp 和 $ anotherProp。 $ newProp 不存在。因此它会创建属性并将其回显两次。但对于 $ anotherProp ,已经存在, < em> else条件 没有触发。这是我面临的两个问题
1.它两次回应财产价值。
2.Else条件根本不起作用。我的意思是如果属性已经 存在它不会打印任何消息。
class myclass {
public $anotherProp='Another property value';
public function __set($prop,$val){
if(! property_exists($this,$prop) ){
$this->prop=$val;
echo $this->prop;
}else{
echo 'property already exists';
}
}
}
$obj=new myclass();
$obj->newProp='i am a new property';
$obj->anotherProp='i am another property';
答案 0 :(得分:3)
在您的__set()
中,您无意中创建了另一个名为public
的 $this->prop
属性,因为您不使用变量$prop
确定哪个属性获取其值集。随后的echo
发生了两次,因为这个尚未创建的属性称为__set()
。
使用$this->$prop
解决其中的一部分,并查看PHP documentation on "variable variables",您可以在其中找到变量对象属性的示例。
public function __set($prop, $val) {
if (!property_exists($this, $prop)) {
// Set the property dynamically
$this->$prop = $val;
echo $this->$prop;
}
else {
echo 'property already exists';
}
}
现在,property already exists
在$anotherProp
上调用public
时看不到private $anotherProp = 'i am another property';
的原因是__set()
is called for inaccessible properties。对于声明为__set()
的属性,不被调用。如果您改为声明
{{1}}
您将看到调用{{1}}方法并打印已存在消息。
答案 1 :(得分:2)
首先,你有一个错字
$this->prop = $val;
应该是
$this->$prop = $val;
$this->prop
表示其名称为&#34; prop&#34;&#39; (=直接参考)。 $this->$prop
表示其名称存储在$ prop`(=间接引用)中的属性。
其次,__set
仅在未定义的属性上调用,所以这个
$obj->someExistingProp = ...
不会致电__set
。这会使您的property_exists
检查基本无效(因为false
中的__set
始终为{{1}}。