__set __get
当我们试图获取一个不可达属性时(比如private),类会自动调用__get
函数。
当试图设置一个不可达属性时(比如private),类会自动调用__set
函数,我们一起来看个例子:
<?php class Person{ public $name = '周伯通'; private $sex = '男'; function __get($name){ echo '个人信息:'.$name.$this->sex; } } $class = new Person(); echo $class->sex;//个人信息:sex男
<?php class Person{ public $name = '周伯通'; private $sex = '男'; function __set($name, $val){ echo '个人信息:'.$name. $val; } } $class = new Person(); $class->sex = '女'; echo $class->sex;
个人信息:sex女 ( ! ) Fatal error: Uncaught Error: Cannot access private property Person::$sex in G:\web\gitlearn\set.php on line 11 ( ! ) Error: Cannot access private property Person::$sex in G:\web\gitlearn\set.php on line 11
<?php class Person{ public $name = '周伯通'; private $sex = '男'; function __set($name, $val){ //echo '个人信息:'.$this->$name = $val; $this->$name = $val; //注意 这里是$name,是要设置访问的变量名,如果大家用$this->name,会看到本例会输出的是 男 } function getSex(){ echo $this->sex; //获取新的属性 } } $class = new Person(); $class->sex = '女'; echo $class->getSex();// 输出 女