• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

这段代码为何会输出father?

php 搞代码 3年前 (2022-01-25) 14次浏览 已收录 0个评论
文章目录[隐藏]
<code><?phpclass father{    public function __construct()    {        $this->init();    }    private function init()    {        echo "father\n";    }}class son extends father{    public function init()    {        echo "son\n";    }}$son  = new son();</code>

回复内容:

<code><?phpclass father{    public function __construct()    {        $this->init();    }    private function init()    {        echo "father\n";    }}class son extends father{    public function init()    {        echo "son\n";    }}$son  = new son();</code>

因为son里的init方法是public,而father的init方法是private,这个其实表示你son里的init方法并没有重写父类里的方法。那自然调用的仍然是父类自己的实现了

<code>$son.init(); // son</code>

<code>php</code><code><br>class father{    public function __construct()    {        // $this->init();      static::init();//php5.6    }    private function init()    {        echo "father\n";    }}class son extends father{    /*public function __construct()    {        $this->init();    }*/    public function init()    {        echo "son\n";    }}</code>

后期静态绑定

Reference: http://docs.php.net/manual/en/language.oop5.late-static-bindings.php

Note:
In non-static contexts, the called class will be the class of the object instance. Since $this-> will try to call private methods from the same scope, using static:: may give different results. Another difference is that static:: can only refer to static properties.

<code>class father{    public function __construct()    {        $this->init();    }    private function init()    {        echo "father\n";    }}class son extends father{    public fun<a style="color:transparent">来@源gao*daima.com搞@代#码网</a><strong>搞gaodaima代码</strong>ction __construct()    {        parent::__construct();        $this->init();    }    private function init()    {        echo "son\n";    }}new son();</code>

输出

<code>fatherson</code>

建议查看__construct基础知识,想告诉楼主踏实一点,我就不信你弄清了里面的方法还会来问
授之以渔

private方法无法被重写

father中的init如果是public或protected,那么是会输出son;但是现在是private,所以在father中调用init是不会输出son的,而是调father的int输出father。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:这段代码为何会输出father?
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址