简体   繁体   English

在__construct中创建的PHP对象在同一类的函数内部不可用

[英]PHP Object created in __construct Not Accesible inside function of same Class

PHP website developed using MVC pattern. 使用MVC模式开发的PHP网站。 i want access an object created using constructor in all functions of class. 我想访问在类的所有函数中使用构造函数创建的对象。 when i check is_object its not there so i create object one more time. 当我检查is_object它不在那里,所以我再创建对象一次。

When try to simulate the MVC pattern its working fine( below code ) getting Object Accessible: $this->ldap Logged In! 当尝试模拟MVC模式时,它的工作正常( 以下代码 )( Object Accessible: $this->ldap Logged In!Object Accessible: $this->ldap Logged In! . But in my actual website getting as Non-Object: $this->ldap Logged In! 但是在我的实际网站上却变成了Non-Object: $this->ldap Logged In!

What could be possible mistakes i done? 我可能犯了什么错误? is there anyway to find what is the issue? 无论如何找到问题所在?

class ldap{
    function ldap_userAuth(){
        return TRUE;
    }
}

class commonfunctions {
    private $ldap;
    public function __construct(){
        $this->ldap=new ldap();
    }
    function userLogin(){
        if(!is_object($this->ldap)){
            $this->ldap=new ldap();
            echo 'Non-Object: $this->ldap'.PHP_EOL;
        }
        else{ 
            echo 'Object Accessible: $this->ldap'.PHP_EOL; 
        }
        if($this->ldap->ldap_userAuth()){
            return TRUE;
        }
        else{ 
            return FALSE; 
        }
    }
}

class Model extends commonfunctions {
}

class Controller {
    public $model;

    public function __construct(){  
        $this->model = new Model(); 
    }

    public function invoke(){
        if($this->model->userLogin()){
            echo 'Logged In!'.PHP_EOL;
        }
        else{ 
            echo 'Logged Out!'.PHP_EOL; 
        }
    }
}

$controller = new Controller();
$controller->invoke();

Note:- classes are included in the above order for my actual website. 注意:以上课程中包含了我的实际网站的课程。 Above Code snippet is working as expected i have issue only in live website. 上面的代码片段按预期工作,我只在实时网站中有问题。

Try calling the __construct method of the parent in the Model class like this: 尝试像这样在Model类中调用父级的__construct方法:

class Model extends commonfunctions {
    public function __construct(){
        parent::__construct();
    }
}

to make sure that the constructor is being called. 确保正在调用构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM