发布于 1970-01-01 08:00
  • 7 个回答
    • 因为son里的init方法是public,而father的init方法是private,这个其实表示你son里的init方法并没有重写父类里的方法。那自然调用的仍然是父类自己的实现了

      2022-12-01 16:44 回答
    • $son.init(); // son
      
      2022-12-01 16:44 回答
    • php
      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"; } }

      后期静态绑定

      2022-12-01 16:44 回答
    • 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.

      class father
      {
          public function __construct()
          {
              $this->init();
          }
      
          private function init()
          {
              echo "father\n";
          }
      }
      
      class son extends father
      {
          public function __construct()
          {
              parent::__construct();
              $this->init();
          }
      
          private function init()
          {
              echo "son\n";
          }
      }
      
      new son();
      

      输出

      father
      son
      
      2022-12-01 16:44 回答
    • 建议查看__construct基础知识,想告诉楼主踏实一点,我就不信你弄清了里面的方法还会来问
      授之以渔

      2022-12-01 16:44 回答
    • private方法无法被重写

      2022-12-01 16:44 回答
    • father中的init如果是public或protected,那么是会输出son;但是现在是private,所以在father中调用init是不会输出son的,而是调father的int输出father。

      2022-12-01 16:44 回答
    撰写答案
    今天,你开发时遇到什么问题呢?
    立即提问
    PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有