Home >Backend Development >PHP Tutorial >PHP magic method function and usage example analysis
The examples in this article describe the functions and usage of php magic methods. Share it with everyone for your reference, the details are as follows:
<?php //php中的魔术方法 header('content-type:text/html;charset=utf-8'); class Person{ public $name; protected $sex; private $salary; //构造方法,实例化对象是自动触发的方法 public function __construct($name,$sex,$salary){ $this->name=$name; $this->sex=$sex; $this->salary=$salary; } //魔术常量__CLASS__ public function getClassName(){ echo __CLASS__; } // __FUNCTION__ public function getMethod(){ echo __FUNCTION__; } //__tostring() public function __tostring(){ return '对象必须用var_dump()'.'姓名是'.$this->name; } //__clone() 在使用clone方法的时候会自动调用 public function __clone(){ echo '这个对象是被克隆出来的'; $this->name='李四'; } //__get() 当调用一个不存在或权限不够的属性自动触发的方法 public function __get($a){ echo $a.'属性不存在或权限不够'; } //__set() 当设置一个不存在或权限不够的属性时自动触发的方法 public function __set($name,$value){ echo $name.'为'.$value; } //__isset() 当在类外判断一个不存在或权限不够的属性时自动触发的方法 public function __isset($name){ echo $name.'不能为空'; } //__call() 当去访问一个权限不够或者不存在的方法的时候,会自动触发的魔术方法 public function __call($method,$a){ echo '您请求的方法'.$method.'不存在'; $this->getname(); } public function getname(){ echo $this->name; } } //实例化对象 $person=new Person('张三','男',12223); $person1=new Person('张三','男',12223); //$person2=new Person('李四','女',11111); var_dump($person); var_dump($person1); exit; $person->getClassName(); $person->getMethod(); //echo $person->name; //echo $person; $person1=$person; //同一个对象 //var_dump($person); //var_dump($person1); $person2=clone $person; //克隆会产生不一样的对象 //var_dump($person); //var_dump($person2); //echo $person2->name; //$person->salary=10000; //var_dump(isset($person->salary)); //$person->getName();
The above is the analysis of the functions and usage examples of PHP magic methods. For more related content, please pay attention to the PHP Chinese website (www.php. cn)!