如果在类中定义了一个常量:
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”访问常量
答案 0 :(得分:2)
这是PHP解析器的一个令人遗憾的缺点。这将有效:
$example = $this->example;
$min = $example::MIN_VALUE;
这不是:
$min = $this->example::MIN_VALUE;
编辑:
PHP bug#63789:https://bugs.php.net/bug.php?id=63789
中记录了此问题它已被修复,但你必须等到PHP的下一个主要版本(7)。
答案 1 :(得分:1)
这是一个类常量。没有必要(实际上没有任何手段)以基于实例的方式访问它。
您只需将其作为Example::MIN_VALUE
访问即可消除任何混淆。
PHP> 5.3允许通过你所显示的实例进行访问(即$class_instance::CLASS_CONSTANT
),但这仍然不能与该实例的属性相混淆,该属性可以通过->
访问(如果是公共的话)。 / p>
答案 2 :(得分:0)
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
,这意味着该变量的值在执行期间不会发生变化,这就是为什么你不要#&# 39; t需要实例化一个对象来访问它的值。
希望它清楚!