// 当调用不存在的方法时,__call会被自动调用,
// 还会自动传给__call两个参数,
// 分别代表被调用的不存在的方法名
// 和调用时传递的参数
class sharp {
public function __call($m,$arg) {
$cnt = count($arg);
if($cnt == 3) {
return $arg[0] + $arg[1] + $arg[2];
} else if($cnt == 4) {
return $arg[0] * $arg[1] * $arg[2] * $arg[3];
} else {
return '未知类型';
}
}
}
header('content-type:text/html;charset=utf-8');
$sharp = new sharp();
echo $sharp->area(1,2,3);//输出6
如果写成下面的样子就是错的,因为php不像java那样通过方法名相同而参数不同来实现重载。
class sharp {
public function __call($m,$arg) {
$cnt = count($arg);
if($cnt == 3) {
return $arg[0] + $arg[1] + $arg[2];
} else if($cnt == 4) {
return $arg[0] * $arg[1] * $arg[2] * $arg[3];
} else {
return '未知类型';
}
}
public function area($a,$b){
return $a*$b;
}
public function area($a,$b,$c){
return $a*$b*$c;
}
}
header('content-type:text/html;charset=utf-8');
$sharp = new sharp();
echo $sharp->area(1,2);//会报错,说方法重定义了
PHP5 中重载可以通过 __get, __set, and __call 几个特殊方法来进行。当 Zend 引擎试图访问一个成员并没有找到时,PHP将会调用这些方法。
在以下示例中,__get和__set代替所有对属性变量数组的访问。如果必要,你还可以实现任何类型你想要的过滤。例如,脚本可以禁止设置属性值, 在开始时用一定的前缀或包含一定类型的值。__call 方法说明了你如何调用未经定义的方法。你调用未定义方法时,方法名和方法接收的参数将会传给__call方法, PHP传递__call的值返回给未定义的方法。
<?php
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;
}
public function __call($method, $p)
{
print("Invoking $method()<br>\n");
//print("Arguments: ");
//print_r($args);
if($method == 'display')
{
if(is_object($p[0]))
$this->displayObject($p[0]);
else
if(is_array($p[0]))
$this->displayArray($p[0]);
else
$this->displayScalar($p[0]);
}
}
public function displayObject($p)
{
echo ("你传入的是个对象,内容如下:<br>");
print_r($p);
echo "<hr>";
}
public function displayArray($p)
{
echo ("你传入的是个数组,内容如下:<br>");
print_r($p);
echo "<hr>";
}
public function displayScalar($p)
{
echo ("你传入的是个单独变量,内容如下:<br>" . $p);
echo "<hr>";
}
}
header('content-type:text/html;charset=utf-8');
$o = new Overloader();
//调用 __set() 给一个不存在的属性变量赋值
$o->dynaProp = "Dynamic Content";
//调用 __get()
print($o->dynaProp . "<br>\n");
//调用 __call()
$o->dynaMethod("Leon", "Zeev"); //输出:Invoking dynaMethod()
$o->display(array(1,2,3));
//输出:Invoking display()
//你传入的是个数组,内容如下:
//Array ( [0] => 1 [1] => 2 [2] => 3 )
$o->display('Cat');
//输出:Invoking display()
//你传入的是个单独变量,内容如下:
//Cat
?>