zoukankan      html  css  js  c++  java
  • ThinkPHP之__construct()和__initialize()

    本文转自:http://blog.csdn.net/e421083458/article/details/16339711/

    ThinkPHP中的__initialize()和类的构造函数__construct()
    网上有很多关于__initialize()的说法和用法,总感觉不对头,所以自己测试了一下。将结果和大家分享。不对请更正。
    首先,我要说的是
    1、__initialize()不是php类中的函数,php类的构造函数只有__construct().
    2、类的初始化:子类如果有自己的构造函数(__construct()),则调用自己的进行初始化,如果没有,则调用父类的构造函数进行自己的初始化。
    3、当子类和父类都有__construct()函数的时候,如果要在初始化子类的时候同时调用父类的__constrcut(),则可以在子类中使用parent::__construct().

    如果我们写两个类,如下:

    [php] view plain copy
     
     print?
    1. class Action{  
    2.     public function __construct()  
    3.     {  
    4.         echo 'hello Action';  
    5.     }  
    6. }  
    7. class IndexAction extends Action{  
    8.     public function __construct()  
    9.     {  
    10.         echo 'hello IndexAction';  
    11.     }  
    12. }  
    13. $test = new IndexAction;  
    14. //output --- hello IndexAction  


    很明显初始化子类IndexAction的时候会调用自己的构造器,所以输出是'hello IndexAction'。
    但是将子类修改为

    [php] view plain copy
     
     print?
    1. class IndexAction extends Action{  
    2.     public function __initialize()  
    3.     {  
    4.         echo 'hello IndexAction';  
    5.     }  
    6. }  


    那么输出的是'hello Action'。因为子类IndexAction没有自己的构造器。
    如果我想在初始化子类的时候,同时调用父类的构造器呢?

    [php] view plain copy
     
     print?
    1. class IndexAction extends Action{  
    2.     public function __construct()  
    3.     {  
    4.         parent::__construct();  
    5.         echo 'hello IndexAction';  
    6.     }  
    7. }  


    这样就可以将两句话同时输出。
    当然还有一种办法就是在父类中调用子类的方法。

    [php] view plain copy
     
     print?
    1. class Action{  
    2.     public function __construct()  
    3.     {  
    4.         if(method_exists($this,'hello'))  
    5.         {  
    6.             $this -> hello();  
    7.         }  
    8.         echo 'hello Action';  
    9.     }  
    10. }  
    11. class IndexAction extends Action{  
    12.     public function hello()  
    13.     {  
    14.         echo 'hello IndexAction';  
    15.     }  
    16. }  


    这样也可以将两句话同时输出。
    而,这里子类中的方法hello()就类似于ThinkPHP中__initialize()。
    所以,ThinkPHP中的__initialize()的出现只是方便程序员在写子类的时候避免频繁的使用parent::__construct(),同时正确的调用框架内父类的构造器,所以,我们在ThnikPHP中初始化子类的时候要用__initialize(),而不用__construct(),当然你也可以通过修改框架将__initialize()函数修改为你喜欢的函数名。 

  • 相关阅读:
    如果控制文件损坏那么如何恢复?恢复控制文件的方式有哪几种
    【OCP|OCM】Oracle培训考证系列
    【RMAN】Oracle中如何备份控制文件?备份控制文件的方式有哪几种?
    在高并发、高负载的情况下,如何给表添加字段并设置DEFAULT值?
    CentOS 7.1静默安装11.2.0.3 64位单机数据库软件
    造成错误“ORA-12547: TNS:lost contact”的常见原因有哪些?
    如何让oracle DB、监听和oem开机启动(dbstart)
    ipcs、ipcrm、sysresv、kernel.shmmax
    【DG】利用闪回数据库(flashback)修复Failover后的DG环境
    【BBED】BBED模拟并修复ORA-08102错误
  • 原文地址:https://www.cnblogs.com/patf/p/6905414.html
Copyright © 2011-2022 走看看