PHP类中常用魔术方法概览
1. __construct()与__destruct()
这两个方法分别在对象实例创建或销毁时触发,均支持接收零个或多个参数。
class A
{
function A()
{
echo "build A";
}
function __destruct()
{
echo "destroy A";
}
}
$obj = new A();
//unset($obj);
Note:The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.
自PHP 5.3.3版本起,若类定义在特定命名空间中,以类名命名的方法不再被视为构造函数;未使用命名空间的类仍保持原有行为。例如:
namespace Foo;
class Bar {
public function Bar() {
// treated as constructor in PHP 5.3.0-5.3.2
// treated as regular method as of PHP 5.3.3
}
}
若不存在namespace Foo;声明,则Bar()依然作为构造函数处理。此外,若出现以下情形:
function __construct()
{
echo "construct A";
}
function A()
{
echo "build A";
}
function __destruct()
{
echo "destroy A";
}
}
即同时定义了__construct()和与类名同名的函数,系统将仅调用__construct()。
2. __call()与__callStatic()
当尝试调用类中不存在的方法时,将触发此方法。它接收两个参数:第一个为方法名称,第二个为传入参数的数组。
class MethodTest
{
public function __call($name, $arguments)
{
// Note: value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(' ', $arguments). "
";
}
public static function __callStatic($name, $arguments)
{
// Note: value of $name is case sensitive.
echo "Calling static method '$name' "
. implode(' ', $arguments). "
";
}
}
$obj = new MethodTest;
$obj->runTest('in','object','context');
MethodTest::runTest('in','static','context');
$arguments以数组形式传入。运行结果如下:
Calling object method 'runTest' in object context Calling static method 'runTest' in static context
还需注意函数的作用域限制,如protected和private:
class TestMagicCallMethod {
public function foo()
{
echo __METHOD__.PHP_EOL."
";
}
public function __call($method, $args)
{
echo __METHOD__.PHP_EOL."
";
if(method_exists($this, $method))
{
$this->$method();
}
}
protected function bar()
{
echo __METHOD__.PHP_EOL."
";
}
private function baz()
{
echo __METHOD__.PHP_EOL."
";
}
}
$test = new TestMagicCallMethod();
$test->foo();
/**
* Outputs:
* TestMagicCallMethod::foo
*/
$test->bar();
/**
* Outputs:
* TestMagicCallMethod::__call
* TestMagicCallMethod::bar
*/
$test->baz();
/**
* Outputs:
* TestMagicCallMethod::__call
* TestMagicCallMethod::baz
*/
3. __get()与__set()
当试图读取对象中不存在的属性时,会调用该方法。
注:可利用此机制实现类似Java反射的各种操作。
class Test
{
public function __get($key)
{
echo $key . " not exists";
}
public function __set($key,$value)
{
echo $key . " = ".$value;
}
}
$t = new Test();
echo $t->name."
";
$t->name = "abc";
输出示例: name not exists name = abc
4. __toString()
该功能类似于Java的toString()方法,当直接打印对象时自动调用,且必须返回一个字符串类型值。
class Test
{
private $name = "abc";
private $age = 12;
public function __toString()
{
return "name : $this->name, age : $this->age";
}
}
$t = new Test();
echo $t;
输出结果:
name : abc, age : 12