简体   繁体   English

PHP 5.3和'::'

[英]PHP 5.3 and '::'

I started into PHP with 5.3 and am using the '::' to access constants ex; 我从5.3开始使用PHP,并使用'::'访问常量ex;。 class::const. class :: const。 However, when I try to use my code in an older PHP namely 5.1.6 and 5.2.12, I get an error that the '::' is unexpected. 然而,当我尝试使用我的代码在一个较旧的PHP 5.1.6,即5.2.12和,我得到一个错误的“::”是一个意外。

How do I access constants in these older versions of PHP5? 如何访问这些旧版本PHP5的常数?

ClassName::constant should work. ClassName::constant应该起作用。 According to the documentation , the following syntax is new in PHP 5.3: 根据文档 ,PHP 5.3中新增了以下语法:

$classname = "MyClass";
echo $classname::constant . "\n"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::constant."\n"; // As of PHP 5.3.0

A more complete code example/reduction may help with debugging. 较完整的代码示例/精简可能有助于调试。

It should be: 它应该是:

ClassName::CONSTANT_NAME

This should work in all versions of PHP 5. 这应该适用于所有版本的PHP 5。

With the :: operator you can call only the static methods or access to the static variables/constants of a class. 使用::运算符,您只能调用静态方法或访问类的静态变量/常量。
The proper way is className::method() or className::publicVariable. 正确的方法是className :: method()或className :: publicVariable。 Inside the static methods you can't refer to this because it's not called on a object, but from a non-static method you can access to a static varibale. 在静态方法内部,您不能引用它,因为它不是在对象上调用的,但是从非静态方法中,您可以访问静态变量。

Anyway, the only new feature of PHP 5.3 about the :: operator is the ability to use a $string that contains the className. 无论如何,PHP 5.3关于::运算符的唯一新功能是可以使用包含className的$ string的功能。

Post please the revelant part of the code 请发布代码的相关部分

I had the same problem accessing class constants via the class name so I resorted to getters: 我在通过类名访问类常量时遇到了同样的问题,所以我求助于getters:

public function getSomeConstant() {
    return self::SomeConstant;
}

and in the parts where I needed it: 在我需要的部分:

className::getSomeConstant();

Edit: in PHP < 5.3 that is... 编辑:在PHP <5.3中...

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

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