Execute PHP class without `new` keyword?

I'm using the keyword new

, so I was surprised to find that the following also works for instantiation.

class MyClass
{
    const CONSTANT = 'constant value';

    function showConstant() {
        echo  self::CONSTANT;
    }
}

// $classname = new MyClass;
$classname = "MyClass";

echo $classname::CONSTANT; 

      

I cannot find any documentation related to this online. Can anyone help me?

+3


source to share


3 answers


Since PHP 5.3.0 it is possible to reference a class using the variable [0]

You are not instantiating an object. This way you are not creating a class. PHP constants can be accessed statically.



[0] http://php.net/manual/en/language.oop5.constants.php

0


source


It is not an instance, with four dots (: :) you can access a static variable, method or constant in this case.



0


source


In fact $classname

, that's another way of saying it MyClass

. So it $classname::CONSTANT

matches MyClass::CONSTANT

. But no instantiation takes place, since execution $classname->showConstant()

doesn't work !!

0


source







All Articles