我是php世界的新手,我试图了解__set()魔术方法在php中的工作方式,在这里我使用__set()方法创建了一个新属性。我有一个if语句来检查该属性是否已经存在如果不存在,那么它将创建属性并为其分配值。在此,我正在检查两个属性。它们是$ newProp和$ anotherProp。 $ newProp不存在。因此它创建了属性并两次回显它的值。但是对于已经存在的$ anotherProp,则没有触发else条件。这是我面临的两个问题

1.它回显了属性值两次。

2.其他条件根本不起作用,我的意思是如果财产已经
存在,它不打印任何消息。

      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()中,您意外地隐式创建了另一个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的原因是__set() is called for inaccessible properties。对于声明为public的属性,不会调用它。如果您改为声明

private $anotherProp = 'i am another property';


您将看到__set()方法被调用,并打印已经存在的消息。

Here's the whole thing in action

关于php - __set()方法两次回显属性值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28126121/

10-11 22:14
查看更多