你如何超越自我?

How do you override self?

我想构建 class 来实现很多基于它的 id 的方法, 所以我想要一个 class parent 来实现这些方法! 当我想使用这个 class 时,我将扩展它并覆盖 id 变量:

 class parent
    {
       $id = "parent";
       private __construct()
       { 
       }

       public static function create_instance()
       {
          $instance = new self();
          return $instance;
       }

       public static function print_id()
       {
          echo $this->id;
       }




    }

class child extend parent
{
   $id = "child";

}

$instance = child::create_instance();
$instance->print_id();

结果将是 "parent",但我希望结果是 child? 怎么做?

EDIT :我也试过这个并得到 parent 而不是 child:

class parent1 {
    private $id = "parent";
    public function __construct() {
    }
    public static function create_instance() {
        $instance = new static ();
        return $instance;
    }
    public function print_id() {
        echo $this->id;
    }
}
class child extends parent1 {
    private $id = "child";
}

$instance = child::create_instance ();
$instance->print_id ();

当前,当您在子 class 上调用 create_instance 方法时,创建的结果是父 class 的实例,而不是您期望的子 class。

在父 class "create_instance" 方法中使用后期静态绑定:

public static function create_instance()
{
    $instance = new static();
    return $instance;
}

更多详情http://php.net/manual/en/language.oop5.late-static-bindings.php

问题是 $id 的可见性是私有的,而它应该受到保护,因为 print_id() 仅在父级上定义;因此它只能达到它自己的 $id.

class parent1 {
    protected $id = "parent";
    // ...
}

class child extends parent1 {
    protected $id = "child";
}

替代方案当然是覆盖子 class 中的 print_id()