zoukankan      html  css  js  c++  java
  • thinkphp中__construct与_initialize()的区别

    (我的环境是wamp,使用了TP框架):

    创建的FatherAction.class.php文件

    <?php


    class FatherAction extends Action{
      public function __construct(){
        echo 'father';
      }
    }

    ?>

    创建的SonAction.class.php文件

    <?php


    class SonAction extends FatherAction{
      public function __construct(){
        echo 'son';
      }
    function index(){

    }
    }

    ?>

    运行子类SonAction里的index()可以看到输出的结果:

    son

    如果将子类改为:

    <?php


    class SonAction extends FatherAction{
       public function __construct(){
        parent::__construct();
        echo 'son';
       }
      function index(){

      }
    }

    ?>

    运行结果为;

    fatherson

    上面的结果可以得出结论:

    在执行子类的构造函数时并不会自动调用父类的构造函数,如果你要调用的话,那么要加上parent::__construct()

    当我们把上述的构造方法改为THINKPHP_initialize()方法时运行会发现:结果与前面的一致,若要执行父类的_initialize()方法,也需要使用这一句:

    parent::_initialize()

    那是不是说明php自带的构造函数__construct()与THINKPHP的_initialize()方法一样的呢?

    先贴上两段代码:

    <?php


    class FatherAction extends Action{
      public function __construct(){
        echo 'father';
      }
    }

    ?>

    <?php


    class SonAction extends FatherAction{
      public function _initialize(){
        echo 'son';
      }


      function index(){

      }

    }

    ?>

    当执行子类SonAction的index方法时发现,输出的结果为:father

    即子类调用了父类的构造函数,而没有调用子类的_initialize()方法

    再贴上两段代码:

    <?php


    class FatherAction extends Action{
      public function __construct(){
        if(method_exists($this,"hello")){
          $this->hello();
        }
        echo 'father';
      }
    }

    ?>

    <?php


    class SonAction extends FatherAction{
      public function _initialize(){
        echo 'son';
      }
      function index(){

      }

      function hello(){
        echo 'hello';
      }
    }

    ?>

    执行子类SonAction的index方法,发现输入的结果为hellofather

    由此可以得出结论:

      当THINKPHP的父类有构造函数而子类没有时,THINKPHP不会去执行子类的_initialize();

      当THINKPHP的父类子类均有构造函数时,要调用父类的构造函数必须使用parent::__construct()-----------------_initialize()同理;

      当THINKPHP的子类同时存在__construct构造函数和_initialize()方法,只会执行子类的__construct构造函数(这个本人亲测,上述代码没有)。

    本文摘自:http://www.cnblogs.com/zyp-itlife/p/5880733.html

  • 相关阅读:
    软件工程14—第09组 Beta冲刺(2/4)
    软件工程13—第09组 Beta冲刺(1/4)
    软件工程12—第09组 Alpha事后诸葛
    软件工程11—第09组 Alpha冲刺(4/4)
    软件工程10—第09组 Alpha冲刺(3/4)
    软件工程09—第09组 Alpha冲刺(2/4)
    软件工程08—第09组 Alpha冲刺(1/4)
    软件工程07—第09组 团队Git现场编程实战
    软件工程06—亚瑟王の十三水2.0
    第06组 Alpha冲刺(4/6)
  • 原文地址:https://www.cnblogs.com/jiafeimao-dabai/p/7423016.html
Copyright © 2011-2022 走看看