繁体   English   中英

从 PHP5 中的抽象方法访问类常量

[英]Accessing class constant from abstract method in PHP5

我试图获取扩展类的常量的值,但是在抽象类的方法中。 像这样:

abstract class Foo {
        public function method() {
            echo self::constant;
        }
    }

    class Bar extends Foo {
        const constant = "I am a constant";
    }

    $bar = new Bar();
    $bar->method();

然而,这会导致致命错误。 有没有办法做到这一点?

这不可能。 一种可能的解决方案是创建一个虚拟方法,该方法返回子类中的所需值,即

abstract class Foo {
  protected abstract function getBar();

  public function method() {
    return $this->getBar();
  }
}

class Bar extends Foo {
  protected function getBar() {
    return "bar";
  }
}

这可以使用 PHP 5.3 中引入的 Late Static Binding 关键字实现

本质上, self指的是编写代码的当前类,而static指的是运行代码的类。

我们可以将您的代码片段重写为:

abstract class Foo {
    public function method() {
        echo static::constant;    // Note the static keyword here
    }
}

class Bar extends Foo {
    const constant = "I am a constant";
}

$bar = new Bar();
$bar->method();

但是,这种编码模式很脏,您可能应该在父类和子类之间引入受保护的 api 来来回汇集此类信息。

所以从代码组织的角度来看,我更倾向于Morfildur提出的解决方案。

暂无
暂无

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

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