I am used to the new
keyword, so I was surprised to find that the following works for instantiation as well.
class MyClass
{
const CONSTANT = 'constant value';
function showConstant() {
echo self::CONSTANT;
}
}
// $classname = new MyClass;
$classname = "MyClass";
echo $classname::CONSTANT;
I can't seem to find any documentation pertaining to this online. Would someone help me out?
As of PHP 5.3.0, it's possible to reference the class using a variable [0]
You're not creating an instance of an object. So you're not instantiating a class. PHP constants can be access statically.
This is not an instantiation, with the four dots (::) you can access an static variable, method or constant in this case.
In fact $classname
is just another way to say MyClass
. So $classname::CONSTANT
is the same as MyClass::CONSTANT
. But there is not instantiation going on, as doing $classname->showConstant()
would not work!!