php - 在 PHP 5.2 中,如何在子类中创建一个常量以用于父类中的方法?

标签 php inheritance constants

编辑:
*注意:很遗憾,我目前使用的是 PHP 5.2。我找不到像样的廉价主机提供 5.3...


在 PHP 中,self 指的是定义被调用方法的类。这意味着如果您不重写子类中的方法,关键字 self 将引用父类,即使是从子类中调用也是如此。

例如,这段代码:

<?php

class ParentClass {
  const NAME = "ParentClass";
  public function showName() {
    echo self::NAME . "<br />\n";
  }
}

class ChildClass extends ParentClass {
  const NAME = "ChildClass";
  public function __construct() {
    echo self::NAME . "<br />\n";
  }
}

$test = new ChildClass();
$test->showName();

?>

将创建此输出:

ChildClass
ParentClass

我想做的是创建一个默认方法(例如上面示例中的 showName()),该方法存在于父类中,其常量定义要使用的默认值。在子项中,我希望能够覆盖这些常量(注意上面子项定义中的 const),并在我调用子项实例的方法时使用这些值。

简而言之,我怎样才能使上面示例的输出是...

ChildClass
ChildClass

...无需在子项中复制父项的代码?

最佳答案

尝试

function showName() {
   return static::NAME;
}

这使用 late static binding :

As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.

More precisely, late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced by self::, parent::, static::, or, if going up in the class hierarchy, forward_static_call(). The function get_called_class() can be used to retrieve a string with the name of the called class and static:: introduces its scope.

编辑:对于 5.2.x

如果您没有 5.3.0,您将无法利用它。一种常见的 hack 解决方案是创建一个由子类名引用的静态缓存(例如 private static $statics = array())。它要求您跟踪对象继承以覆盖 __construct 上的值,并明确定义哪些静态是“可继承的”。例如,SilverStripe在 Sapphire ORM 中使用此技术来绕过 PHP 静态绑定(bind)限制。他们定义了一个 base Object class , 以及各种静态变量管理函数。

关于php - 在 PHP 5.2 中,如何在子类中创建一个常量以用于父类中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4404548/

相关文章:

php - 检查 session 变量是否由其名称的第一部分设置

php - 当包含特定文件扩展名时如何将类添加到超链接?

java - 从类和接口(interface)重新继承静态字段

c++ - 从 C++ 中的 const 成员函数修改引用成员

自定义模块级常量的 Python 类型提示

php - Mysql docker 容器上的 Symfony 4 连接

php - 在 Laravel 中缓存每个数据库查询是否健康?

objective-c - 在不覆盖父 getter/setter 的情况下合成 ivar 声明

Python 使用自定义 __new__ 子类化一个类

Java - 重命名枚举常量