__set($property, $value) 方法用来设置对象的私有属性
当试图设置对象中未定义的属性时,就会触发__set()方法,调用参数为被设置的属性名和属性值
示例代码如下:
<?php class Person { private $name; private $age; public function __construct($name="", $age=25) { $this->name = $name; $this->age = $age; } public function __set($property, $value) { if ($property=="age") { if ($value > 150 || $value < 0) { return; } } $this->$property = $value; } public function say(){ echo "My name is ".$this->name.",I'm ".$this->age." years old"; } } $Person=new Person("John", 25); // 注意下面的代码会改变初始值 $Person->name = "Lili"; // "name" 属性成功赋值。如果没有 __set() 方法,程序就会抛出异常 $Person->age = 16; // "age" 属性成功赋值 $Person->age = 160; // 160 是个非法值,所以赋值失败 $Person->say(); // 输出:My name is Lili, I'm 16 years old.
输出结果如下:
My name is Lili, I'm 16 years old
登录后可发表评论