致命错误:未捕获错误:从堆栈跟踪中的无效上下文调用私有数据:: __ construct():#0 include()#1 {main}在C中引发

时间:2017-10-30 10:00:39

标签: php

class datas {

    public $host = DB_HOST;
    public $user = DB_USER;
    public $pass = DB_PASS;
    public $db_name = DB_NAME;


    public $link;
    public $error;

        private function __construct(){

            $this->connect();

        } 

    private function connect(){

        $this->link = new mysqli($this->host,$this->user,$this->pass,$this->db_name);

        if(!$this->link){

            $this->error ="COnnection failed" . $this->connect_error; 
        }


}

我该如何解决这个问题

1 个答案:

答案 0 :(得分:2)

__construct()函数应为public,而不是private。请注意,属性$host$user$pass$db_name$link$error可以声明为私有,因为它们可能不应该是可从对象外部访问。

class datas {

    private $host = DB_HOST;
    private $user = DB_USER;
    private $pass = DB_PASS;
    private $db_name = DB_NAME;


    private $link;
    private $error;

        public function __construct(){

            $this->connect();

        } 

    private function connect(){

        $this->link = new mysqli($this->host,$this->user,$this->pass,$this->db_name);

        if(!$this->link){

            $this->error ="COnnection failed" . $this->connect_error; 
        }
    }
 }