0

I am wondering how I can use a predefined constant as a class name with the scope resolution operator.

In the PHP documentation, they show an example using a variable, however, I wanted to know if its possible to use a constant.

Example:

class MyClass {
    function MyFunction(){
        return "hi";
    }
}

#This works (returns hi)
echo MyClass::MyFunction();
#This works too
$variable_class="MyClass";
echo $variable_class::MyFunction();

#This doestn work (returns Class 'constant_class' not found)
#define("constant_class", "MyClass");
#echo constant_class::MyFunction(); 
#This doestn work either
const constant_class="MyClass";
echo constant_class::MyFunction();  
Ernesto
  • 605
  • 1
  • 13
  • 30
  • 1
    You're calling the method statically even though the method isn't static. From PHP 7 and later, that would throw a deprecation warning. You should create an instance first. Since PHP 7, you can simply do: `echo (constant_class)::theMethod();` – M. Eriksson May 22 '19 at 13:36
  • Thanks @MagnusEriksson for the answer!! – Ernesto May 22 '19 at 14:38
  • Sorry @nigel-ren for the repeat! – Ernesto May 22 '19 at 14:39

0 Answers0