设置未声明的属性

时间:2018-05-30 10:49:27

标签: php

你可以在没有声明的情况下调用属性“example”吗?为什么这段代码仍然有效?为什么回声只打印一次而不是两次。

class SetMissing {
        public function __set($name, $value) {
            echo "_SET";
            $this->$name = filter_var($value, FILTER_SANITIZE_STRING);
        }
    }
    $obj = new SetMissing();
    $obj->example = "<strong>hello</strong>";
    echo $obj->example . PHP_EOL ;
    $obj->example = "<strong>hello</strong>";
    echo $obj->example;

1 个答案:

答案 0 :(得分:0)

因为__set是一个写入不可访问或不存在的属性的魔术函数。您可以使用魔术__get方法访问不可访问或不存在的属性。

使用内联评论:

$obj = new SetMissing(); // Create object
$obj->example = "hello"; // Propery doesn't exist. Call __set, create a property with name "example" and value "hello" on the object
echo $obj->example . PHP_EOL ; // Access the property because it exists
$obj->example = "hello"; // Overwrite value
echo $obj->example; // Access it again

另外,your example does echo twice

相关问题