简体   繁体   English

PHP:如何扩展库?

[英]Php: How to extend a library?

For a project I use a mysql library called meekrodb and I want to make an extended class with my own mysql functions, so if the library is updated I have only re-edit the extended class. 对于一个项目,我使用一个名为meekrodb的mysql库,并且希望使用自己的mysql函数制作一个扩展类,因此,如果该库已更新,则只能重新编辑该扩展类。

As a beginning programmer I've tried to extend the library as followed: 作为一个入门的程序员,我尝试了如下扩展库:

require './libs/meekrodb.2.0.class.php';
class Database_extend extends MeekroDB  {
protected $db;
protected $database='';

function __construct($server=null, $user=null, $pass=null, $database=null)
{   
    // Creating a database object

$this->db= parent::__construct();  
    //$this->db= parent::__construct($server,$user,$pass,$database);  
    $this->database=$database;

} */
 public function table_exists($tableName=null) {
 if(is_null($tableName )){ 
 trigger_error("Error in: ".__METHOD__." Missing table name.",E_USER_ERROR);     
 }
 else{
$sql = "SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = '$this->database' AND table_name = '$tableName'";
$exists=$this->db->query($sql);
if($exists['count']>0)
{  return TRUE;}
else { return FALSE;}
}  
}#-table_exists

If I test this class (test.php) 如果我测试此类(test.php)

 require './config.inc.php';
 require './libs/Session.php';
 require_once './libs/Ngram.class.php';   
 require_once './libs/Database_extend.class.php';
 /*require_once './libs/meekrodb.2.0.class.php';*/

 DB::$user=DB_USER;
 DB::$password=DB_PASS;
 DB::$dbName=DB_DATABASE;
 $db1=new Database_extend(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
 $t=$db1->query("SELECT * FROM temp LIMIT 0,1");
 //var_dump($t); //THIS WORKS
 var_dump($db1->table_exists('tem')); // THIS DOESN'T work

I get a ' Call to a member function query() on a non-object' error which means that the db variable is not an object. 我收到“在非对象上调用成员函数query()的错误”,这意味着db变量不是对象。

How can I solve this correctly? 我该如何正确解决呢?

The first thing that comes to mind is that you don't pass on the initialization parameters here: 首先想到的是,您无需在此处传递初始化参数:

$this->db= parent::__construct();  

Your override method receives $server, $user, $pass, $database , but you don't make them available to the original code. 您的重写方法将接收$server, $user, $pass, $database ,但您不使它们可用于原始代码。 Hencewhy it won't correctly set up the $db property. 因此,为什么它不能正确设置$db属性。

Also you overwrite $this->db . 同样,您覆盖$this->db But the parent constructor would certainly assign it itself. 但是父级构造函数肯定会为其本身分配。

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

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