重载
PHP 所提供的重载是指动态地创建类属性和方法。是通过魔术方法来实现的。当调用当前环境下未定义或不可见的类属性或方法时,重载方法会被调用。所有的重载方法都必须被声明为 public
。传统的重载是用于提供多个同名的类方法,但各方法的参数类型和个数不同。
在给不可访问属性赋值时, __set()
会被调用。
<?php
class Foo
{
/**
* Set the value of the specified property.
*
* @param string $name
* @param string $value
* @return void
*/
public function __set(string $name, string $value)
{
$this->$name = $value;
}
}
$foo = new Foo();
$foo->property = 'foo';
var_dump($foo->property); // string(3) "foo"
读取不可访问属性的值时, __get()
会被调用。
<?php
class Foo
{
/**
* Private property.
*
* @var string
*/
private string $property = 'foo';
/**
* Return the specified property.
*
* @param string $name
* @return string
*/
public function __get(string $name): string
{
return $this->$name;
}
}
$foo = new Foo();
var_dump($foo->property); // string(3) "foo"
当对不可访问属性调用 isset()
或 empty()
时, __isset()
会被调用。
<?php
class Foo
{
/**
* Private property.
*
* @var string
*/
private string $property = 'foo';
/**
* Check the specified property.
*
* @param string $name
* @return bool
*/
public function __isset(string $name): bool
{
return isset($this->$name);
}
}
$foo = new Foo();
var_dump(isset($foo->property)); // bool(true)
当对不可访问属性调用 unset()
时, __unset()
会被调用。
<?php
class Foo
{
/**
* Private property.
*
* @var string
*/
private string $property = 'foo';
/**
* Check the specified property.
*
* @param string $name
* @return bool
*/
public function __isset(string $name): bool
{
return isset($this->$name);
}
/**
* Unset the specified property.
*
* @param string $name
* @return void
*/
public function __unset(string $name)
{
unset($this->$name);
}
}
$foo = new Foo();
var_dump(isset($foo->property)); // bool(true)
unset($foo->property);
var_dump(isset($foo->property)); // bool(false)
在对象中调用一个不可访问方法时, __call()
会被调用。
<?php
class Foo
{
/**
* Return the specified string.
*
* @param string $name
* @param array $args
* @return string
*/
public function __call(string $name, array $args): string
{
return $name . '+' . implode('+', $args);
}
}
$foo = new Foo();
var_dump($foo->method('foo', 'bar')); // string(14) "method+foo+bar"
在静态上下文中调用一个不可访问方法时, __callStatic()
会被调用。
<?php
class Foo
{
/**
* Return the specified string.
*
* @param string $name
* @param array $args
* @return string
*/
public static function __callStatic(string $name, array $args): string
{
return $name . '+' . implode('+', $args);
}
}
var_dump(Foo::method('foo', 'bar')); // string(14) "method+foo+bar"