php - 在 PHP 中扩展一个类

标签 php class extend

class A{
  private static $instance;

  public static function getInstance(){

    if(!(self::$instance instanceof self))
      self::$instance = new self();

    return self::$instance;
  }

  public function doStuff(){
    echo 'stuff';
  }


}

class B extends A{
  public function doStuff(){
    echo 'other stuff';
  }
}

A::getInstance()->doStuff(); // prints "stuff"

B::getInstance()->doStuff(); // prints "stuff" instead of 'other stuff';

我做错了什么?

为什么 B 类不运行它的功能?

最佳答案

getInstance中的代码:

 if(!(self::$instance instanceof self))
       self::$instance = new self();

所有这些 self 都指向 A,而不是被调用的类。 PHP 5.3 引入了一个叫做 "late static binding" 的东西。 ,它允许您指向被调用的类,而不是代码所在的类。您需要使用 static 关键字:

class A{
  protected static $instance;  // converted to protected so B can inherit

  public static function getInstance(){
    if(!(static::$instance instanceof static))
      static::$instance = new static(); // use B::$instance to store an instance of B

    return static::$instance;
  }

  public function doStuff(){
    echo 'stuff';
  }
}

不幸的是,如果您至少没有 PHP 5.3,这将失败。

关于php - 在 PHP 中扩展一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7419224/

相关文章:

php - 使用 PHP 解码 Microsoft 翻译器 API 的 JSON 输出

php - 将 Laravel 应用程序集成到插件面板内的 Wordpress(管理员)

JavaScript 原型(prototype)错误

Java 泛型类 < ?扩展接口(interface) > 作为参数

c# - 如何防止拆箱 - 读取任意 sql 行时装箱内存开销

javascript - 在 JavaScript 中扩展基类 Array

xslt - 匹配从 XSLT 中的类型继承的节点

php - 读取字段,使其在 pimcore CMS 中不可编辑,因为响应性导致重复字段

当用户仍在网站上时 PHP session 过期

r - 将列表 append 到 R 中的列表列表