php 是否支持方法重载。在尝试下面的代码时,它建议它支持方法重载。任何视图
class test
{
public test($data1)
{
echo $data1;
}
}
class test1 extends test
{
public test($data1,$data2)
{
echo $data1.' '.$data2;
}
}
$obj = new test1();
$obj->test('hello','world');
由于我重载了该方法,因此它将输出为"hello world"。上面的代码片段表明 php 支持方法重载。所以我的问题是 php 是否支持方法重载。
您应该区分方法重写(您的示例(和方法重载
下面是一个简单的示例,如何使用__call魔术方法在 PHP 中实现方法重载:
class test{
public function __call($name, $arguments)
{
if ($name === 'test'){
if(count($arguments) === 1 ){
return $this->test1($arguments[0]);
}
if(count($arguments) === 2){
return $this->test2($arguments[0], $arguments[1]);
}
}
}
private function test1($data1)
{
echo $data1;
}
private function test2($data1,$data2)
{
echo $data1.' '.$data2;
}
}
$test = new test();
$test->test('one argument'); //echoes "one argument"
$test->test('two','arguments'); //echoes "two arguments"
所以我的问题是 php 是否支持方法重载(?
是的,但不是那样,而且,在您的示例中,它并不表明这种重载是正确的,至少对于它的 5.5.3 版和 error_reporting(E_ALL)
.
在该版本中,当您尝试运行此代码时,它会为您提供以下消息:
Strict Standards: Declaration of test1::test() should be compatible
with test::test($data1) in /opt/lampp/htdocs/teste/index.php on line 16
Warning: Missing argument 1 for test::test(), called in /opt/lampp/htdocs/teste/index.php
on line 18 and defined in /opt/lampp/htdocs/teste/index.php on line 4
Notice: Undefined variable: data1 in /opt/lampp/htdocs/teste/index.php on line 6
hello world //it works, but the messages above suggests that it's wrong.
在这两种情况下,您都忘记在测试前添加"函数"。方法被调用子类,因为当您从子类对象调用方法时,它首先检查该方法是否存在于子类中,如果不存在,则它查看继承的父类,并查看公共或受保护检查的可见性,如果方法存在,然后根据该结果返回结果。