Home  >  Article  >  Backend Development  >  第十一节重载[11]_PHP

第十一节重载[11]_PHP

WBOY
WBOYOriginal
2016-06-01 12:38:19676browse

PHP4中已经有了重载的语法来建立对于外部对象模型的映射,就像Java和COM那样. PHP5带来了强大的面向对象重载,允许程序员建立自定义的行为来访问属性和调用方法.

重载可以通过__get, __set, and __call几个特殊方法来进行. 当Zend引擎试图访问一个成员并没有找到时,PHP将会调用这些方法.

在例6.14中,__get和__set代替所有对属性变量数组的访问. 如果必要,你可以实现任何类型你想要的过滤. 例如,脚本可以禁止设置属性值, 在开始时用一定的前缀或包含一定类型的值.

__call方法说明了你如何调用未经定义的方法. 你调用未定义方法时,方法名和方法接收的参数将会传给__call方法, PHP传递__call的值返回给未定义的方法.

Listing 6.14 User-level overloading
class Overloader
{
private $properties = array();

function __get($property_name)
{
if(isset($this->properties[$property_name]))
{
return($this->properties[$property_name]);
}
else
{
return(NULL);
}
}

function __set($property_name, $value)
{
$this->properties[$property_name] = $value;
}

function __call($function_name, $args)
{
print("Invoking $function_name()
n");
print("Arguments: ");
print_r($args);

return(TRUE);
}
}
$o = new Overloader();

//invoke __set() 给一个不存在的属性变量赋值,激活__set()
$o->dynaProp = "Dynamic Content";

//invoke __get() 激活__get()
print($o->dynaProp . "
n");

//invoke __call() 激活__call()
$o->dynaMethod("Leon", "Zeev");
?>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn