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

    1.类的初始化,一个类如果自身有构造函数,则调用自己的构造函数进行初始化,如果没有,则调用父类的构造函数进行初始化

    class Action{

      public function __construct()

      {

        echo 'hello Action';

      }

    }

    class IndexAction extends Action{

      public function __construct()

      {

        echo 'hello IndexAction';

      }

    }

    $test=new IndexAction;    //输出hello IndexAction

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

    如果将子类修改为:

    class IndexAction extends Action

    {

      public function __initialize()

      {

        echo `hello IndexAction`;

      }

    }

    就会输出`hello Action` 。 因为子类IndexAction没有自己的构造器,所以就会在初始化的时候调用父类的构造器

    2.如果子类父类都有构造函数的时候,初始化子类调用父类的构造函数,可以在子类构造函数里使用 parent::construct();

    在初始化子类的同时调用父类的构造器

    class IndexAction extends Action{

      public function __construct()

      {

        parent::__construct();

        echo 'hello IndexAction';

      }

    }

    3.thinkPHP中的initalize() 的出现只是方便程序员在写子类进行初始化的时候避免频繁的使用parent::construct()

    还有一种方法就是在父类中调用子类的方法:

    class Action{

      public function __construct()

      {

        if(method_exists($this,'hello'))

        {

          $this->hello();

        }

        echo 'hello Action';

      }

    }

    class IndexAction extends Action{

      public function hello()
      {

        echo 'hello IndexAction';

      }

    }

    此处子类中的hello方法就类似thinkPHP中的__initialize()

    class Api extends Controller

    {

      protected $user;

      public function __initialize()

      {

        $this->request=Request::instance();

      }

    }

  • 相关阅读:
    前端接口设计
    前端协作流程
    编写jQuery插件
    jQuery插件之validation插件
    深入理解ajax系列第九篇——jQuery中的ajax
    前端学PHP之Smarty模板引擎
    第3选择-解决所有难题的关键思维,种下好的种子避免落入钻石交易
    阿里BCG重磅报告《人工智能,未来致胜之道》
    关于web开发前端h5框架的选择
    html5+php实现文件的断点续传ajax异步上传
  • 原文地址:https://www.cnblogs.com/ymdphp/p/10905563.html
Copyright © 2011-2022 走看看