我是 php 世界的新手。我试图了解 __set() 魔术方法在 php 中的工作原理。这里我使用 __set() 创建一个新属性__set() em> 方法。我有一个 if 语句,用于检查该属性是否已存在。如果不存在,则它创建该属性并为其分配一个值。这里我正在检查两个属性。它们是$newProp 和 $anotherProp . $newProp不存在。因此它创建该属性并两次回显其值。但是对于已经存在的 $anotherProp,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';
最佳答案
在您的 __set()
中,您不小心创建了另一个名为 $this->prop
的 public
属性隐式是因为您不使用变量 $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';
}
}
现在,在 $anotherProp
上调用时看不到属性已存在
的原因是 __set()
is called for inaccessible properties 。对于声明为 public
的属性,不会调用它。如果您改为声明
private $anotherProp = 'i am another property';
您将看到调用了__set()
方法并打印了已经存在消息。
关于php - __set() 方法回显属性值两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28126121/