PHP Codeigniter - parent::__construct

2022-08-30 18:40:42

当从PHP中的父类继承时,特别是在Codeigniter中,有什么作用?parent::__construct or parent::model()

如果我不上家长班,会有什么不同?而且,建议使用哪种方式?__construct

-已添加-

重点更多地放在Codeigniter上,具体是关于根据版本以不同的方式调用,以及如果Codeigniter会自动执行此操作,是否可以省略这一点。parent::__construct


答案 1

这是一个普通的类构造函数。让我们看一下下面的例子:

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'

如您所见,类 B 从 A 继承所有值和函数。因此,可以从 A 和 B 访问类成员。由于我们在类 B 中添加了一个构造函数,因此在创建类 B 的新对象时,将不使用类 A 的构造函数。$some_var

现在看一下以下示例:

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

如您所见,因为我们尚未声明构造函数,所以隐式使用类 A 的构造函数。但是我们也可以执行以下操作,这相当于类C:

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

因此,仅当您希望子类中的构造函数执行某些操作并执行父构造函数时,才需要使用该行。给出的示例:parent::__construct();

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

更多信息可以在这里找到:http://php.net/manual/en/language.oop5.php


答案 2

parent::__construct 或 parent::model() 做什么?

这些函数的作用完全相同,只是在 PHP5 之前,构造函数以前是以类本身命名的。我说在你的例子中,你正在扩展Model类(在一些旧版本的CI上,因为你不需要使用CI_model),如果我在这个__construct是正确的,那么它与model()相同)。


推荐