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();

      }

    }

  • 相关阅读:
    关于软件工程的理解
    二人编程项目----五子棋
    多线程单元测试
    软件工程的 理解和问题
    教务管理系统软件设计说明书
    团队分组
    结对项目:贪吃蛇
    使用JUNIT等工具进行单元测试
    学习软件工程现存问题
    对unit4测试的初步认知
  • 原文地址:https://www.cnblogs.com/ymdphp/p/10905563.html
Copyright © 2011-2022 走看看