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

时间:2015-01-24 13:43:00

标签: php get set magic-methods

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

2 个答案:

答案 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}}方法并打印已存在消息。

Here's the whole thing in action

答案 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}}。