1,808   PHP

一,魔术方法

1,__toString()
直接echo $obj时会被调用,需要返回一个字符串

2,__call($function_name,$arguments)
调用不存在的方法时会被调用,包含两个参数,第一个为方法名,第二位传参

3,__callStatic()
调用不存在的静态方法时被调用,也是包含两个参数,同上

4,__sleep()
serialize对象时会被调用,用于睡眠前做数据清理

5,__wakeup()
unserialize对象时被被调用,用于初始化操作

 

二,示例代码

class test{
	
	private $username,$age;

	public function __construct() {
		$this->username='hello';
		$this->age=25;
		echo 'initializing',"\n";
	}
	
	// 直接输出对象时会被执行
	public function __toString(){
		return 'test';
	}
	
	// 调用不存在的方法时会别执行
	// 为了调用出错之后,让程序能继续执行下去
	public function __call($function_name,$arguments){
		echo 'function_name '.$function_name.' is not exist',"\n";
		echo 'arguments',"\n";
		var_dump($arguments);
		echo "\n";
	}
	
	// 调用不存在的静态方法时会别执行
	// 为了调用出错之后,让程序能继续执行下去
	static function __callStatic($function_name,$arguments){
		echo 'static function_name '.$function_name.' is not exist',"\n";
		echo 'arguments',"\n";
		var_dump($arguments);
		echo "\n";
	}	
	
	// serialize对象时会被调用,用于睡眠前做数据清理
	public function __sleep()
    {
        return array('username','age');
    }
    // unserialize对象时被被调用,用于初始化操作
    public function __wakeup()
    {
        echo 'after wakeup to do something';
    }

}
$test = new test();
echo 'echo obj',"\n";
echo $test,"\n";

echo "\n";
echo 'testFunction not exist',"\n";
$test->testFunction('is it exist');

echo "\n";
echo 'testStaticFunction not exist',"\n";
$test::testStaticFunction('is it exist');

echo "\n";
echo 'test sleep',"\n";
$s_obj = serialize($test);
var_dump($s_obj);


echo "\n";
echo 'test wakeup',"\n";
$us_obj = unserialize($s_obj);
var_dump($us_obj);

 

三,测试结果

 

initializing
echo obj
test

testFunction not exist
function_name testFunction is not exist
arguments
array(1) {
  [0]=>
  string(11) "is it exist"
}


testStaticFunction not exist
static function_name testStaticFunction is not exist
arguments
array(1) {
  [0]=>
  string(11) "is it exist"
}


test sleep
string(70) "O:4:"test":2:{s:14:"testusername";s:5:"hello";s:9:"testage";i:25;}"

test wakeup
after wakeup to do somethingobject(test)#2 (2) {
  ["username":"test":private]=>
  string(5) "hello"
  ["age":"test":private]=>
  int(25)
}



Leave a Reply

Your email address will not be published. Required fields are marked *