I started into PHP with 5.3 and am using the '::' to access constants ex; 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.
How do I access constants in these older versions of PHP5?
ClassName::constant
should work. According to the documentation , the following syntax is new in 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.
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. 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.
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:
public function getSomeConstant() {
return self::SomeConstant;
}
and in the parts where I needed it:
className::getSomeConstant();
Edit: in PHP < 5.3 that is...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.