如果在类中定义了一个常量,如下所示:
class Example
{
const MIN_VALUE = 0.0; // RIGHT - Works INSIDE of a class definition.
}
可以像这样访问常量:
Example::MIN_VALUE
但是如果你这样做:
class Sample {
protected $example;
public function __construct(Example $example){
$this->example = $example;
}
public function dummyAccessToExampleConstant(){
//doesn't work -> syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)
if($this->example::MIN_VALUE === 0.0){
}
//this works
$tmpExample = $this->example;
if($tmpExample::MIN_VALUE === 1){
}
}
}
有人可以解释我这种行为的原因吗?
是否有充分的理由,或者它只是一种阻止访问的语言结构 "::"
有没有办法用"$this"访问常量
这是PHP解析器的不幸缺点之一。这将起作用:
$example = $this->example;
$min = $example::MIN_VALUE;
这不会:
$min = $this->example::MIN_VALUE;
编辑:
此问题记录在 PHP 错误 #63789 中:https://bugs.php.net/bug.php?id=63789
它已被修复,但您必须等到 PHP 的下一个主要版本 (7)。
它是一个
类常量。不需要(实际上也没有办法)以基于实例的方式访问它。
您应该Example::MIN_VALUE
访问它以消除任何混淆。
PHP> 5.3 允许通过您所示的实例进行访问(即 $class_instance::CLASS_CONSTANT
),但这仍然不能与可以通过->
访问的实例的属性混淆(当然,如果是公共的)。
Is there a way how to access a constant with "$this"
你不需要用$this
访问常量,因为$this
指的是current instanciated object of a class
。 常量可以在不实例化对象的情况下访问。
Is there a good reason or is it just a language construct ...
一个常量,顾名思义,它是一个constant value
,这意味着该变量的值在执行过程中不会改变,这就是为什么你不需要实例化一个对象来访问它的值。
希望清楚!