PHP重写方法规则

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP重写方法规则脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚读完这本书:
“在 PHP 5中,除了构造函数之外,任何派生类在重写方法时必须使用相同的签名”
评论中的PHP手册:
“在重写中,方法名称和参数(arg)必须相同.
例:
class P {public function 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();

这将输出

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

解决方法

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

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

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

变化:

>可见性:受保护 – >上市;增加可见性是兼容的(相反会导致错误).>参数:无变化(必需参数数量相同)

脚本宝典总结

以上是脚本宝典为你收集整理的PHP重写方法规则全部内容,希望文章能够帮你解决PHP重写方法规则所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。