【问题标题】:Calling a parent method from a child class从子类调用父方法
【发布时间】:2014-06-11 12:50:06
【问题描述】:

我在类继承方面遇到了一些困难。我有 5 个类,所有这些类都使用创建、更新和删除方法访问我的数据库,这些方法我已经抽象化,以便我可以将它们推送到 MasterDatabase 类中,然后让它们都扩展这个类。我遇到的问题是基本继承概念。我浏览了 SOF,很多人都问过类似的问题,但不是这个问题。

  class DatabaseMaster {

    public function  create() {
        $attributes = $this->attributes();
        $question_marks = array();
        foreach ($attributes as $key => $value) {
        $question_marks[] = "?";
         }
        $place_holder = array_intersect_key($attributes, get_object_vars($this));
        $place_holder = array_values($place_holder);
        $sql = "INSERT INTO ".self::$table_name." (";
        $sql .= join(", ", array_keys($attributes));
        $sql .= ") VALUES (";
        $sql .= join(", ", array_values($question_marks));
        $sql .= ")";
        $query = $handler->prepare($sql);
        $query->execute($place_holder);
   }

 }

现在,如果我有一个类用户。我希望这个扩展DatabaseMaster,我想它不能像上面那样继承这个create函数?例如,我的问题是我在方法中对 $this->attributes 的引用。 DatabaseMaster 没有属性,但我的 User 类当然有。如果我运行 $user->create();它不起作用,我认为是因为这个。如何克服这个问题?对于目前过度使用 SOF,我深表歉意!

这行得通....

 public function  create() {
    $attributes = $this->attributes();
    $question_marks = array();
    foreach ($attributes as $key => $value) {
    $question_marks[] = "?";
    }
    $place_holder = array_intersect_key($attributes, get_object_vars($this));
    $place_holder = array_values($place_holder);
    $sql = "INSERT INTO users (";
    $sql .= join(", ", array_keys($attributes));
    $sql .= ") VALUES (";
    $sql .= join(", ", array_values($question_marks));
    $sql .= ")";
    $query = $handler->prepare($sql);
    $query->execute($place_holder);
}

所以我的问题很明显......如何在方法中使表名动态化,以便在孩子调用它时引用孩子?

【问题讨论】:

  • 这里的问题是对 SELF::$TABLE_NAME 的引用。你可以这样在父方法中调用'self'并期望它在子调用方法时引用子表名吗?

标签: php class inheritance methods parent-child


【解决方案1】:

可以“按原样”解释该方法。考虑以下示例:

class P {

        function create() {
                echo $this->attributes . "\n";
        }
}

class C extends P {
        public $attributes = "hello!";
}

$c = new C;

$c->create();

这正如您所期望的那样工作,并且父级上的 create() 方法与子级中定义的 $attributes 的值相呼应。

【讨论】:

  • 你没有错..我可以看到你的例子工作正常。虽然我不能让我的用户继承这个创建函数....
猜你喜欢
  • 2017-11-09
  • 2012-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多