鍍金池/ 問答/PHP/ Error: Using $this when not in object co

Error: Using $this when not in object context

class Events
{
    protected $db='';
      protected function __construct()
       {
          $this->db = new Workerman\MySQL\Connection('localhost', '3306', 'wx_entercode_cn', 'guwansifang', 'wx_entercode_cn');
       }


       public function test(){
            $this->db->insert('chat_record')->cols(array(
                'to_msg'=>$message_data['to_client_id'],
                'from_msg'=>$message_data['from_client_id'],
                'content'=>$message_data['content']))->query();
       }
}
$Events=new Events();
$Events->test();

為什么test方法中不能使用$this->db?

回答
編輯回答
好難瘦
  1. 構(gòu)造函數(shù)改成public function __construct()
  2. protected $db = '';改成protected $db = null;
  3. 查看Connection類返回
protected function __construct()
       {
          $db = new Workerman\MySQL\Connection('localhost', '3306', 'wx_entercode_cn', 'guwansifang', 'wx_entercode_cn');
          var_dump($db);
          $this->db = $db;
       }
  1. 如果還不行,將__construct()中的代碼改到test()試試
2017年4月30日 02:39
編輯回答
毀與悔
protected function __construct()

改為

public function __construct()
2017年8月31日 13:31