PHP Codeigniter - parent::__construct

后端 未结 3 1490
别跟我提以往
别跟我提以往 2020-12-07 21:42

When getting inherited from a parent class in PHP, especially in Codeigniter what does parent::__construct or parent::model() do?

How would it make diff

相关标签:
3条回答
  • 2020-12-07 21:54

    It will simply execute the constructor of parent class

    0 讨论(0)
  • 2020-12-07 22:07

    This is a normal class constructor. Let's look at the following example:

    class A {
        protected $some_var;
    
        function __construct() {
            $this->some_var = 'value added in class A';
        }
    
        function echo_some_var() {
            echo $this->some_var;
        }
    }
    
    class B extends A {
        function __construct() {
            $this->some_var = 'value added in class B';
        }
    }
    
    $a = new A;
    $a->echo_some_var(); // will print out 'value added in class A'
    $b = new B;
    $b->echo_some_var(); // will print out 'value added in class B'
    

    As you see, class B inherits all values and functions from A. So the class member $some_var is accessible from A as well as from B. Because we've added a constructor in class B, the constructor of class A will NOT be used when you are creating a new object of class B.

    Now look at the following examples:

    class C extends A {
        // empty
    }
    $c = new C;
    $c->echo_some_var(); // will print out 'value added in class A'
    

    As you can see, because we have not declared a constructor, the constructor of class A is used implicitly. But we can also do the following, which is equivalent to class C:

    class D extends A {
        function __construct() {
            parent::__construct();
        }
    }
    $d = new D;
    $d->echo_some_var(); // will print out 'value added in class A'
    

    So you only have to use the line parent::__construct(); when you want a constructor in the child class to do something, AND execute the parent constructor. Example given:

    class E extends A {
        private $some_other_var;
    
        function __construct() {
            // first do something important
            $this->some_other_var = 'some other value';
    
            // then execute the parent constructor anyway
            parent::__construct();
        }
    }
    

    More information can be found here: http://php.net/manual/en/language.oop5.php

    0 讨论(0)
  • 2020-12-07 22:08

    what does parent::__construct or parent::model() do?

    these functions do exactly the same, only the construct function used to be named after the class itself prior to PHP5. I say in your example you are extending the Model class (and on some older version of CI since you don't need to use CI_model), if I'm correct in this __construct is the same as model().

    0 讨论(0)
提交回复
热议问题