繁体   English   中英

如何在子类中创建一个常量,以便在PHP 5.2中的父类中找到的方法中使用?

[英]How can I create a constant in a subclass to be used in a method found in a parent class in PHP 5.2?

编辑:
* 注意:遗憾的是,我目前正在使用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;
}

这使用后期静态绑定

从PHP 5.3.0开始,PHP实现了一个称为后期静态绑定的功能,可用于在静态继承的上下文中引用被调用的类。

更确切地说,后期静态绑定通过存储在最后一次“非转发调用”中命名的类来工作。 在静态方法调用的情况下,这是显式命名的类(通常是::运算符左侧的类); 在非静态方法调用的情况下,它是对象的类。 “转发调用”是由self ::,parent ::,static ::引入的静态调用,或者,如果在类层次结构中上传,则为forward_static_call()。 函数get_called_class()可用于检索具有被调用类名称的字符串,static ::引入其范围。

编辑:对于5.2.x

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

我相信你的案例的相应语法盐是:

print constant(get_class($this)."::NAME");

使用static::CONSTNAME将返回正确的值。

也许这仅仅是因为你的简短例子,但似乎并不需要“自我”引用。

我会这样做:

class ParentClass {
  public function showName() {
    echo $this->name() . "<br />\n";
  }

  public static function name() {
    return "ParentClass";
  }
}

class ChildClass extends ParentClass {
  public function __construct() {
    echo $this->name() . "<br />\n";
  }
  public static function name() {
    return "ChildClass";
  }
}

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

输出:

ChildClass
ChildClass

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM