What can I add in constructors in PHP?

China☆狼群 提交于 2019-12-25 03:38:10

问题


Could anyone tell me what I can include in the constructor?

I know that I can do the following.

function  __construct(){
    parent::Controller();
    session_start();

  }

But I am wondering if I can add any variables, if statement etc.

Thanks in advance.


回答1:


Knock yourself out. Add any PHP you want. You can use $this to refer to the object being created.




回答2:


You can include variables, function calls, method calls, object declarations, etc, etc, etc inside your default constructor.

class Test {

    protected $protected;
    private static $static;

    function  __construct() {
        parent::__construct();
        $this->protected = 'test';
        $variable_local = 'hey';
        self::$static = 'im static';
        $obj = new OtherClass();
        $this->myMethod();
        externalFunction();
    }

    public function myMethod() {
        echo 'all mine';
    }

}

function externalFunction() {
    'hey, im external';
}


来源:https://stackoverflow.com/questions/2044055/what-can-i-add-in-constructors-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!