无法在PHP类中使用正确的继承
我在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
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";
}
}