【问题标题】:Cannot use right the inheritance in PHP class无法在 PHP 类中使用正确的继承
【发布时间】:2012-06-22 11:36:54
【问题描述】:

我在 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对象。

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

【问题讨论】:

  • var_dump($this->table);放在getName的开头并在此处显示结果
  • 好吧,我的错,变量 $table 是私有的,所以这是问题所在,我将其更改为公共并且工作正常。
  • 如果您不希望它可公开访问但仍可覆盖,请将其设置为 protected

标签: php sql inheritance constructor


【解决方案1】:

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

class childClass extends parentClass{
     public $table;

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

    public function __construct()
    {

您应该在此处添加parent::__construct()(除非父级仅设置$this->table,但即使这样添加也很好)

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

【讨论】:

    猜你喜欢
    • 2016-06-06
    • 2017-08-25
    • 2018-04-05
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多