如何从PHP中的子函数访问父变量?

时间:2017-01-13 05:42:27

标签: php pdo

这是我的代码:

<?php
class DB {

  public $config = array('DBUSER'=>'root',
                  'DBPASS'=>'',
                  'DBHOST'=>'localhost',
                  'DBNAME'=> 'ninjacks');


   function get_connection() {
    try {
    $db = new PDO('mysql:host='.$this->config['DBHOST'].'; dbname='.$this->config['DBNAME'].'; charset=utf8'
                  , $this->config['DBUSER'], $this->config['DBPASS']);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $ex) {
        echo 'An Error occured! '.$ex->getMessage(); //user friendly message
        return false;
    }

    return $db;
   }
}
?>

<?php
require_once('database.php');

class Base {
   protected $conn;
   protected $db;
   function __construct() {

        $this->db = new DB();
        $this->conn = $this->db->get_connection();
   }
}
?>


<?php
include_once('base.php');

class Session extends Base{

  function __construct() {
    parent::__construct();
  }


  public function connexion($email, $password){
    $sql = "SELECT email, password
            FROM users
            WHERE actif = '1' AND hash = NULL AND email = :email AND password = :password";

    $sth = $this->db->prepare($sql);
    $sth->execute(array(':email' => $email, ':password' => md5($password)));
    $count = $sth->rowCount();

    if($count > 0)
      return true;
    else
      return false;
  }
}
?>

在我的 connexion 功能中,使用$this->db->prepare();时始终收到此错误:

  

不在对象上下文中时使用$ this

我在发布这里之前阅读了很多论坛,我也尝试了2个小时。

1 个答案:

答案 0 :(得分:0)

它不起作用的原因是因为$this->db->prepare()不存在,因为$this->db是您的DB类的实例,它没有prepare()方法。相反,您需要以$this->conn->prepare()

的方式调用它