调用非对象上的成员函数

时间:2013-06-24 12:25:33

标签: php mysqli

我是php oop的新手,所以有点挣扎。

我有一个数据库连接类即:

  class config{

   protected $HOST = "localhost";
   protected $USERNAME = "something" ;
   protected $PASSWORD = "something";
   protected $DATABASE = "something";

// Constructor - open DB connection
function __construct() {

try {
    $this->db = new mysqli($this->HOST, $this->USERNAME, $this->PASSWORD, $this-
    >DATABASE);
    $this->db->autocommit(FALSE);
    }
catch(Exception $e)
    {   
    if($this->db->connect_errno > 0){

    echo 'Caught exception: ',  $e->getMessage(), "\n";
    }
    }

    }

   // Destructor - close DB connection
     function __destruct() {
    $this->db->close();
    }


 }

 $api = new Config();

现在我有另一个类,我需要执行一些任务...但是我得到致命错误。

第二课:

  class Myclass extends config {

   function __construct(){}

   public function myfunction()
   {
    try{


     $stmt = $this->db->stmt_init();   /* Error here : Fatal error: Call to a member                 
                                          function stmt_init() on a non-object */
 $query = "SELECT ABC FROM table " ;

 $stmt = $this->db->prepare($query); /* Error here : Fatal error: Call to a member                 
                                          function prepare() on a non-object   */
      }
     catch(){}

   }

   }

请指导我使用正确的补救措施代码段

2 个答案:

答案 0 :(得分:0)

派生类构造函数不调用基础构造函数,因此$this->db没有它应该具有的值。在PHP you must do this explicitly

在这种特殊情况下,您应该完全删除派生的构造函数,因为它没有做任何事情。这将让PHP直接使用基础构造函数。

答案 1 :(得分:0)

在您的子类中,您需要调用父构造函数。在实例化子类时,PHP不会自动调用父构造函数。

 class Myclass extends config {

     function __construct($h, $u, $p, $d){ parent::__construct($h, $u, $p, $d); }

此外,您在父类中没有$db属性,因此请添加

 class config{

   protected $db;
   protected $HOST = "localhost";
   protected $USERNAME = "something" ;
   protected $PASSWORD = "something";
   protected $DATABASE = "something";

编辑:依赖注入方法:

class config{
   public $HOST = "localhost";
   public $USERNAME = "something" ;
   public $PASSWORD = "something";
   public $DATABASE = "something";
}

class Myclass
{
   protected $db;

   function __construct($db)
   {
      $this->db = $db;
   }

   public function myfunction()
   {
       // do whatever with $this->db
   }
}

$config = new Config();

try
{
    $db = new mysqli($config->HOST, $config->USERNAME, $config->PASSWORD, $config->DATABASE);
    $db->autocommit(FALSE);
}
catch(Exception $e)
{   
    if($db->connect_errno > 0){
        echo 'Caught exception: ',  $e->getMessage(), "\n";
    }
}

$myclass = new Myclass($db);

了解依赖注入。这是处理需要访问数据库的类的有利方法。不要让所有类扩展数据库,只需在创建新类(需要db)时将datsbase对象作为参数传递。

相关问题