对象覆盖PHP

时间:2016-10-30 20:11:06

标签: php oop

我有两个类扩展了另一个类。

但是当第二个对象被实例化时,获得第一个对象的定义。

对象B获取对象A的定义

A类

class a extends Connection{

    public function __construct() { parent::__construct("TOKENS");}

    public function helloA(){
        echo "A";
    }
}

B类

class B extends Connection{

    public function __construct() { parent::__construct("USERLEVEL"); }

    public function helloB(){
        echo "B";
    }
}

班级连接

class Connection extends dbData{

    private $table;

    function __construct($name){
        $this->setTable($name);
        parent::__construct();
    }

    public function setTable($name){
        $this->table = parent::getTable($name);
    }

    public function connectionInsert($info){
        return parent::insert($this->table, $info);
    }

    public function connectionSelect($where="", $bind="", $fields="*"){
        return parent::select($this->table, $where, $bind, $fields);
    }

    public function connectionDelete($where, $bind=""){
        return parent::delete($this->table, $where, $bind);
    }

    public function connectionRun($sql, $bind=""){
        return parent::run($sql, $bind);
    }

    public function connectionEdit($info, $where, $bind){
        return parent::update($this->table, $info, $where, $bind);
    }


}

测试文件

   $a = new a();
   print_r($a);
   $b = new b();
   print_r($b);

结果:

a Object ( [table:Connection:private] => tokens [error:Db:private] => [sql:Db:private] => [bind:Db:private] => [errorCallbackFunction:Db:private] => [errorMsgFormat:Db:private] => )
a Object ( [table:Connection:private] => tokens [error:Db:private] => [sql:Db:private] => [bind:Db:private] => [errorCallbackFunction:Db:private] => [errorMsgFormat:Db:private] => ) 

但是,如果我直接对新A()或新B()

执行print_r
print_r(new a());
print_r(new b());

结果就是我想要的。

a Object ( [table:Connection:private] => tokens [error:Db:private] => [sql:Db:private] => [bind:Db:private] => [errorCallbackFunction:Db:private] => [errorMsgFormat:Db:private] => )
B Object ( [table:Connection:private] => us_level [error:Db:private] => [sql:Db:private] => [bind:Db:private] => [errorCallbackFunction:Db:private] => [errorMsgFormat:Db:private] => ) 

即使我试图访问每个班级的功能,我突然得到错误,说该功能在该班级中不存在。

TESTFILE

$a = new a();
print_r($a->helloA());

$b = new b();
echo "</br>";
print_r($b->helloB());

错误讯息:

Fatal error: Call to undefined method a::helloB() 

所以,在这一点上,我不知道为什么我会覆盖这些对象。

有人可以帮忙吗?

由于

1 个答案:

答案 0 :(得分:1)

我在我的IDE中复制/粘贴你的代码然后运行但没有问题!所以很奇怪,当你创建对象B时,你得到的错误是对象方法(a :: helloB())不存在!如果你把整个代码(包括dbData)我愿意再试一次..