PHP Codeigniter - parent :: __ construct [英] PHP Codeigniter - parent::__construct

查看:357
本文介绍了PHP Codeigniter - parent :: __ construct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在PHP中继承父类时,特别是在Codeigniter中 parent :: __ construct或parent :: model() do?

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

如果我不 __ construct 父类,它会有什么区别?
而且,建议采用哪种方式?

How would it make difference if I don't __construct parent class? And, which way is suggested?

添加 -

重点更多的是Codeigniter具体关于调用 parent :: __构造根据版本不同的方式,以及如果这可以被省略,如果Codeigniter会自动这样做。

The focus is more on Codeigniter specific regarding a call to parent::__construct in different ways depending on versions and also if this could be omitted in case Codeigniter would do this automatically.

推荐答案

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

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'

和函数从A.所以类成员 $ some_var 可以从A和B访问。因为我们在类B中添加了一个构造函数,A类的构造函数

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.

现在看看下面的例子:

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

正如你所看到的,声明一个构造函数,A类的构造函数是隐式使用的。但我们也可以做以下,等同于类C:

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'

所以你只需要使用 parent :: __ construct(); 当你想要一个构造函数在子类中做某事,并执行父构造函数。示例:

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

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

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

这篇关于PHP Codeigniter - parent :: __ construct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆