Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法在PHP类中使用正确的继承_Php_Sql_Inheritance_Constructor - Fatal编程技术网

无法在PHP类中使用正确的继承

无法在PHP类中使用正确的继承,php,sql,inheritance,constructor,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"; $r

我在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是空的,而我希望它是“my_child_table”,只要我有一个childClass对象

有人知道我做错了什么吗?
提前感谢

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

class childClass extends parentClass{
     public $table;
parentClass
已经定义了一个
$table
,因此在子类中重新声明它可能会破坏父类的版本。您必须删除此处的声明。此外,公共可见性并不能很好地封装状态;请改为在父类中使用
protected

    public function __construct()
    {
您应该在此处添加
parent::\uu construct()
(除非parent仅设置
$this->table
,但即使如此,还是可以添加)


var_dump($this->table);
放在
getName
的开头,并在此处显示结果确定我的错误,变量$table是私有的,所以这就是问题所在,我将其更改为public,效果很好。如果不希望它可以公开访问,但仍然可以重写,请将其设置为
protected
        $this->table = "my_child_table";
    }
}