【问题标题】:PHP Overriding methods rulesPHP 覆盖方法规则
【发布时间】:2014-06-28 02:44:34
【问题描述】:

我刚从书中读到:
“在 PHP 5 中,除了构造函数,任何派生类在覆盖方法时都必须使用相同的签名”
来自 cmets 中的 PHP 手册:
"在覆盖中,方法名称和参数(arg's)必须相同。
示例:
类 P { 公共函数 getName(){} }
C 类扩展 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();

这将输出:

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

【问题讨论】:

  • 开启错误显示并将错误级别设置为E_ALL
  • 什么都没发生,它没有显示任何错误。

标签: php


【解决方案1】:

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

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

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

变化:

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

  2. 参数:没有变化(相同数量的必需参数和最大参数数量)

【讨论】:

  • 我试过并得到了这个错误Declaration of ChildController::test($p1) should be compatible with ParentController::test($p1, $p2 = NULL),所以我想我可以补充一下,似乎一个孩子必须有最低限度。参数作为其父对应项(或更多/或可选但数量相同)@Jack 你能支持我吗?
  • @DaniyalNasir 那是因为你的子方法不能用 2 个参数调用,因此它不兼容
【解决方案2】:

PHP 不支持您描述的overloading。但是,参数只能是同一类型(即整数、字符串、数组等)。您可能有特定于覆盖方法的附加参数,但初始参数必须与父类的参数匹配。

这也可能与PHP function overloading 重复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 2011-07-17
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    相关资源
    最近更新 更多