__construct()
每次实例化一个类都会先调用该方法进行初始化
__get + __set 实现未定义属性调用
__get()
当想要获取一个类的私有属性,或者获取一个类并未定义的属性时。该魔术方法会被调用。
__set()
当想要设置一个类的私有属性,或者设置一个类并未定义的属性时。该魔术方法会被调用。
class db{
function a() {
echo 'a';
}
function __set($k, $v) {
//$this->arr[$k] = $v;
echo 'this is __set';
}
function __get($k) {
echo 'this is __get';
}
}
$db = new db;
$db->a(); //a
$db->b='bbb'; //this is __set
$db->b; //this is __get
class db{
protected $arr = [];
function __set($k, $v) {
$this->arr[$k] = $v;
}
function __get($k) {
return $this->arr[$k];
}
}
$db = new db;
$db->b='bbb';
echo $db->b; //bbb
__call 实现未定义方法的调用
__call 和__callStatic
class db
{
function __call($func,$param){
echo 'func:'.$func."<br/>";
echo 'param:'.json_encode($param);
return "<br/>end";
}
static function __callStatic($func,$param){
echo 'func:'.$func;
}
}
$db = new db;
echo $db->test("hello",123); // func:test param:["hello",123] end
db::static_test("hello",123); //func:static_test
__toString 和 __invoke
__toString 把对象当字符串使用的时候调用
__invoke 把对象当函数使用的时候调用
class db{
function __toString() {
return 'str';
}
function __invoke($param='') {
return 'array';
}
}
$db=new db;
echo $db; //str //若未定义__toString()会报错
echo $db(); //array //若未定义__invoke()会报错
网友评论