因为php是弱类型语言,它没办法像其他语言那样实现真正的重载,只能借助魔术方法来实现
<strong>所有魔术方法需定义成共有</strong>
具体有如下魔术方法:
1、__set 给不可访问属性赋值时,自动调用
2、__get 获取不可访问属性时,自动调用
3、__isset 对不可访问属性调用 isset 和 empty时,自动调用
4、__unset 对不可访问属性调用unset时,自动调用
5、__call 访问不可访问方法时,自动调用
6、__callStatic 访问不可访问静态方法时,自动调用
如下代码示例
<?php
class Animal{
private $data = array();
private $a = 1;
protected $b = 2;
public $c = 3;
public function __set($name,$value){
echo "setting $name value = $value";
$this->data[$name] = $value;
}
public function __get($name){
echo "getting $name ";
return $this->data[$name];
}
public function __isset($name){
return isset($this->data[$name]);
}
public function __unset($name){
echo "unsetting $name ";
unset($this->data[$name]);
}
public function __call($name,$param){
echo "function is $name";
echo "<br/>";
var_dump($param);
}
public static function __callStatic($name,$param){
echo "static function is $name";
echo "<br/>";
var_dump($param);
}
}
$animal = new Animal();
$animal->age = 1;
echo "<br/>";
echo $animal->num;
echo "<br/>";
echo $animal->age;
echo "<br/>";
var_dump(isset($animal->age));
echo "<br/>";
unset($animal->age);
echo "<br/>";
echo "<br/>";
echo "<br/>";
echo "调用call<br/>";
$animal->test('hello',array('name'=>'cheng','age'=>20));
Animal::gege();
?>
输出如下