加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP重写方法规则

发布时间:2020-12-13 17:47:25 所属栏目:PHP教程 来源:网络整理
导读:我刚读完这本书: “在 PHP 5中,除了构造函数之外,任何派生类在重写方法时必须使用相同的签名” 从评论中的PHP手册: “在重写中,方法名称和参数(arg)必须相同. 例: class P {public function getName(){}} C类扩展P {public function getName(){}} “ 那么
我刚读完这本书:
“在 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');

变化:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读