PHP 常见魔术方法简单例子
<?php
class Test
{
private $priAttr;
private $data = [];
public $objA;
public $objB;
public $pubAttr;
public function __construct($priAttr, $pubAttr)
{
$this->priAttr = $priAttr;
$this->pubAttr = $pubAttr;
$this->objA = new TestA;
$this->objB = new TestB;
}
public function __get($name)
{
print_r('getting unexist attr => ' . $name . PHP_EOL);
return $this->data[$name] ?: '';
}
public function __set($name, $value)
{
print_r('setting unexist attr => ' . $name . ', value => '. $value . PHP_EOL);
return $this->data[$name] = $value;
}
public function __isset($name)
{
print_r('isset unexist attr => ' . $name . PHP_EOL);
return $this->data[$name] ? true : false;
}
public function __unset($name)
{
print_r('unset unexist attr => ' . $name . PHP_EOL);
unset($this->data[$name]);
return true;
}
public function __call($name, $arguments)
{
print_r('call unexist method => ' . $name . PHP_EOL);
return call_user_func_array([$this, 'xxx'], $arguments);
}
private function xxx($a, $b = '', $c = '')
{
echo 'hello! im xxx method! a:'. $a . ',b:' . $b . ',c:' . $c . PHP_EOL;
}
public static function __callStatic($name, $arguments)
{
print_r('call unexist static method => ' . $name . PHP_EOL);
return call_user_func_array([__CLASS__, 'xxxStatic'], $arguments);
}
private static function xxxStatic($a, $b = '', $c = '')
{
echo 'hello! im xxx static method! a:'. $a . ',b:' . $b . ',c:' . $c . PHP_EOL;
}
public function getPriAttr()
{
return $this->priAttr;
}
public function __invoke()
{
print_r('try to use class '. __CLASS__ .' as method' . PHP_EOL);
}
public function __clone()
{
print_r('clone objA' . PHP_EOL);
$this->objA = clone $this->objA;
}
}
class TestA
{
public $flag = 'testA';
}
class TestB
{
public $flag = 'testB';
}
$test = new Test('priAttr', 'pubAttr');
print_r($test->getPriAttr() . PHP_EOL);// private attr
print_r($test->pubAttr . PHP_EOL);//public attr
$test->a = 'a';//__set
print_r($test->a . PHP_EOL);//__get
$test->hello(1,2,3);//__calll
Test::hi(4,5,6);//__callStatic
$test();//__invoke
$cloneTest1 = clone $test;//clone
$test->pubAttr = 'pubAttr1';
echo $cloneTest1->pubAttr . PHP_EOL;
$test->objA->flag = 'testAA';
echo $cloneTest1->objA->flag . PHP_EOL;
$test->objB->flag = 'testBB';
echo $cloneTest1->objB->flag . PHP_EOL;