PHP __get __set的用法 基类与派生类 <?php /** * __set() 取得当前类中封装过私有属性或者方法重新执行或赋值操作 __get() 取得当前类中封装过属性或方法并转换成共有属性 * @author Administrator * */ class A { private $name='不能更改'; //为私有属性 function __construct($name) { return $this->name = $name; } function __get($outname) { //间接访问私有属性,输出时可以加东西 // echo $outname . "<br>"; // return $this->name."======="; return $this->who().$this->name."===="; } // protected function who(){ // echo __CLASS__; // } function __set($outname, $value) { //可以更改私有属性值,附加条件等 if ($value > "20") { return $this->$outname = $value; } } function __destruct() { //清楚内存 // echo "<p>=========".$this->name."<br>"; } } class B extends A{ /** * 这里重写了方法 A中调用的是子类 * @param */ protected function who(){ echo __CLASS__; } } /** * 外部调用 私有name */ $pc1 = new B("我的电脑"); echo $pc1->safsaf . "<br>"; $pc1->name = "520"; echo $pc1->name;