__set() 方法回显 属性 值两次

__set() method echoing property value twice

我是 php 的新手 world.I 我正在尝试了解 __set() 魔术方法在 php.Here 中的工作原理我使用 __set() method.I 创建了一个新的 属性 有一个 if 语句来检查是否属性 已经存在或 not.If 不存在,然后它创建 属性 并分配给它一个 value.Here 我正在检查两个 properties.They 是 $newProp$anotherProp . $newProp 不会 exists.So 它创建 属性 并为 [=19= 回显它的值 twice.But ]$anotherProp,已经存在,else条件没有trigger.Here i我面临两个问题

1.It 回显 属性 值两次。

2.Else 条件在 all.I 时不起作用意味着如果 属性 已经 存在它不打印任何消息。

      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';

首先,你打错了

$this->prop = $val;

应该是

$this->$prop = $val;

$this->prop 表示 'the property of this whose name is "prop"'(=直接引用)。 $this->$prop 表示“其名称存储在 $prop 中的 属性”(=间接引用)。

其次,__set只在未定义的属性上调用,所以这个

$obj->someExistingProp = ...

没有打电话给 __set。这使您的 property_exists 检查基本上无用(因为它在 __set 中总是 false)。

在你的 __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';
  }
}

现在您在 $anotherProp 上调用它时看不到 property already exists 的原因是 __set() is called for inaccessible properties不是 为声明的属性 public 调用。如果你改为声明

private $anotherProp = 'i am another property';

您将看到调用了 __set() 方法并且打印了 already exists 消息。

Here's the whole thing in action