重写方法规则


PHP Overriding methods rules

我刚从书上读到:
在PHP 5中,除了构造函数之外,任何派生类在重写方法时都必须使用相同的签名
来自PHP手册的注释:
在重写中,方法名和参数(arg 's)必须相同。
例子:
类P{公共函数getName(){}}
类C扩展P{公共函数getName(){}}"

那么为什么我可以用其他参数和它们的数量来代替方法呢?这是合法的还是会在将来触发错误,或者我只是错过了什么?

PHP Version 5.5.11

class Pet {
    protected $_name;
    protected $_status = 'None';
    protected $_petLocation = 'who knows';
// Want to replace this function
    protected function playing($game = 'ball') {
        $this->_status = $this->_type . ' is playing ' . $game;
        return '<br>' . $this->_name . ' started to play a ' . $game;
    }
    public function getPetStatus() {
        return '<br>Status: ' . $this->_status;
    }
}

class Cat extends Pet {
    function __construct() {
        $this->_type = 'Cat';
        echo 'Test: The ' . $this->_type . ' was born ';
    }
// Replacing with this one    
    public function playing($gameType = 'chess', $location = 'backyard') {
        $this->_status = 'playing ' . $gameType . ' in the ' . $location;
        return '<br>' . $this->_type . ' started to play a ' . $gameType . ' in the ' . $location;
    }
}
$cat = new Cat('Billy');
echo $cat->getPetStatus();
echo $cat->playing();
echo $cat->getPetStatus();

这将输出:

测试:猫出生了
状态:没有
猫开始在后院下棋
状态:在后院下棋

规则是方法签名必须与它覆盖的方法兼容。让我们来看看层次结构中的两个方法:

protected function playing($game = 'ball');
public function playing($gameType = 'chess', $location = 'backyard');

更改:

  1. 可见度:protected ->public;增加可见性是兼容的(反之会导致错误)。

  2. 参数:无变化(所需参数数和最大参数数相同)

PHP不支持您所描述的方式的重载。然而,参数必须是相同的类型(即整数,字符串,数组等)。您可以有特定于重写方法的附加参数,但是初始参数必须与父类的参数匹配。

这也可以是PHP函数重载的副本