【问题标题】:PHP abstract class access of constant below下面常量的PHP抽象类访问
【发布时间】:2021-07-18 21:24:07
【问题描述】:

在 PHP 中,抽象类可以访问下面类的常量吗?

例如,我可以在 Generic 中分解 getName 吗?

abstract class Generic {
    abstract public function getName(): string;
}

class MorePreciseA extends Generic {
    private const NAME = "More Precise A";

    public function getName(): string {
        return self::NAME;
    }
}

class MorePreciseB extends Generic {
    private const NAME = "More Precise B";

    public function getName(): string {
        return self::NAME;
    }
}

谢谢

【问题讨论】:

  • 不管它是抽象的,父类没有办法知道子类的属性(即使它不是私有的)。您能否详细说明您要实现的目标?也许我们可以提出不同的设计。

标签: php class static abstract factorization


【解决方案1】:

这就是self::static:: 之间的区别所在。更多信息请参见here

abstract class Generic {
    protected const NAME = "Generic";

    public function getName(): string {
        return self::NAME;
    }
}

class MorePreciseA extends Generic {
    protected const NAME = "More Precise A";
}

class MorePreciseB extends Generic {
    protected const NAME = "More Precise B";

}


$a = new MorePreciseA();
$b = new MorePreciseB();

var_dump($a->getName(), $b->getName());

会导致

// string(7) "Generic"
// string(7) "Generic"

但是如果你像这样替换 Generic 实现

abstract class Generic {
    public function getName(): string {
        return static::NAME;
    }
}

然后会输出

// string(14) "More Precise A"
// string(14) "More Precise B"

【讨论】:

  • 完美,正是我想要的。谢谢!
猜你喜欢
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
  • 2013-02-23
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
相关资源
最近更新 更多