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支持方法重载。
答案 0 :(得分:10)
您应该在method overriding(您的示例)和method overloading
之间做出改动这是一个简单的例子,说明如何使用__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"
答案 1 :(得分:1)
所以我的问题是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.
答案 2 :(得分:0)
在两种情况下,您都忘了在测试前添加'功能'。方法被调用为子类,因为当你从子类对象调用一个方法时,它首先检查子方法中是否存在该方法,如果没有,那么它会查看具有可见性公开或受保护检查的继承父类,如果方法存在则返回根据那个结果。