php中的魔术方法__call(),__clone(),__set(),__get()
__call($a,$v),当在类外部调用类中不存在或者不可见(用protected,private修饰)的方法时,会自动调用__call(方法名,数组参数),此时会向改方法传递2个参数,第一个为调用的方法名,第二个为传递的参数放进数组里。__clone()方法在类的对象被克隆时触发。__set($key,$val)在类外部设置类中不存在或者不可见(protected,private修饰)的属性时触发该方法,此时传递2个参数,第一个是属性名,第二个是属性值。__get($key)在类外部获取类中不存在或者不可见(protected,private修饰)的属性时触发该方法,此时传递1个参数,即为属性名。例子:
<?php
class test{
protected $a=1;
private $b=2;
public function __clone(){
echo "有人要克隆我<br/>";
}
public function __call($name,$arg){
echo "有人要调用不存在或不可见的方法名",$name,",第一个参数是$arg[0]<br/>";
}
public function __set($k,$v){
echo "有人要设置不存在或不可见的属性",$k,"的值为",$v,"<br/>";
}
public function __get($k){
echo "有人要获取不存在或不可见的属性",$k;
}
}
$test1=new test();
$test3=$test1;//此时$test3和$test1是同一个对象,即都指向同一个对象
$test2=clone $test1;//克隆后$test1和$test2是2个不同的对象,虽然存储的值相同
$test1->abc(1,2,3);
$test1->a=3;
$test1->b;
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn