PHP重写方法规则

Pro*_*gZi 4 php

我刚从书中读到:
"在PHP 5中,除了构造函数之外,任何派生类在重写方法时都必须使用相同的签名"
来自注释中的PHP手册:
"在重写中,方法名称和参数(arg)必须相同.
例如:
class P {public function getName(){}}
class C extends P {public function getName(){}}"

那么为什么我能用其他参数和数量替换方法呢?这是合法的还是将来会引发错误,或者我只是遗漏了什么?

PHP版本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();
Run Code Online (Sandbox Code Playgroud)

这将输出:

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

Ja͢*_*͢ck 7

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

protected function playing($game = 'ball');

public function playing($gameType = 'chess', $location = 'backyard');
Run Code Online (Sandbox Code Playgroud)

变化:

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

  2. 参数:无变化(必需参数数量相同)