时间:2021-07-01 10:21:17 帮助过:19人阅读
public function setCity($city){$this->city = $city;}
public function getCity(){return $this->city;}
public function setCountry($country){$this->country = $country;}
public function getCountry(){return $this->country;}
}
class Person{
protected $name;
protected $address;
//浅克隆
public function __construct(){
$this->address = new Address;
}
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
public function __call($method,$arguments){
if(method_exists($this->address,$method)){
return call_user_func_array(array($this->address,$method),$arguments);
}
}
//深克隆
public function __clone(){
$this->address = clone $this->address;
}
}
$test1 = new Person;
$test2 = clone $test1;
$test1->setName('testname1');
$test1->setCity('testcity1');
$test2->setName('testname2');
$test2->setCity('testcity2');
echo $test1->getName().'-'.$test1->getCity()."\n";
echo $test2->getName().'-'.$test2->getCity()."\n";
//testname1-testcity2
//testname2-testcity2
6.重要属性访问(__set __get __isset __unset) __isset __unset5.1之后才有用
作用:拦截对属性的需求,为了提高分离的程度,还要实现__isset()和__unset(),以便当我们用isset来检测属性或者unset()来删除属性,来保证类的行为正确
例:
代码如下:
class Person{
protected $__data = array('email','test');
public function __get($property){
if(isset($this->__data[$property])){
return $this->__data[$property];
}else{
return false;
}
}
public function __set($property,$value){
if(isset($this->__data[$property])){
return $this->__data[$property] = $value;
}else{
return false;
}
}
public function __isset($property){
if(isset($this->__data[$property])){
return true;
}else{
return false;
}
}
public function __unset($property){
if(isset($this->__data[$property])){
return unset($this->__data[$property]);
}else{
return false;
}
}
}
$test = new Person;
$test->email= 'test';
var_dump($test->email);
注意:
这两个方法只会捕捉缺少的属性,如果你为你的类定义了一个属性,那么当访问这个属性时php不会调用__get()和__set();
这两个方法完全破坏了任何属性继承的想法。如果父对象中有个 __get()方法,而你在子类中又实现了自己的__get()方法,那么你的对象不会正确的执行,因为父类的__get()方法永远不会被调用,当然可以用parent::__get()解决
缺点:
速度相对较慢
使用魔术访问器方法就不可能在使用反射类,如phpdocumentor这类的工具将代码自动文档化
不能将其用于静态属性