不能在PHP类中使用正确的继承

时间:2012-06-20 10:36:33

标签: php sql inheritance constructor

我在PHP中有这个父类:

 class parentClass{
    public $table;

    public function __construct(){
       $this->table = "my_parent_table";
    }

    public function getName($id) {
      $strQuery = "SELECT name FROM $this->table WHERE id=$id";

      $result = mysql_query($strQuery);
      if ($result) {
         $row = mysql_fetch_object($result);
         if ($row) {
             return $row->name;
          } else {
             return false;
          }
      } else {      
         return false;
      }
    } 
 }

我还有另一个继承了这个的课程:

 class childClass extends parentClass{
     public $table;

     public function __construct(){
       $this->table = "my_child_table";
     }
 }

然后在我正在做的另一个文件中:

 $myObj = new childClass();
 $name = $myObj->getName('1');

现在的问题是getName函数有一个空表,所以变量$ this-> table为null,而我希望它是“my_child_table”,只要我有一个childClass对象。

有谁知道我做错了什么? 提前致谢

1 个答案:

答案 0 :(得分:1)

不确定,但这看起来很棘手:

class childClass extends parentClass{
     public $table;

parentClass已经定义了$table,因此在子类中重新声明它可能会破坏父类的版本。你必须在这里删除声明。此外,公众可见度并没有真正完全封装国家;请改为在父级中使用protected

    public function __construct()
    {

你应该在这里添加parent::__construct()(除非父母只设置$this->table,但即使这样,添加也很好)

        $this->table = "my_child_table";
    }
}