Skip to content
Advertisement

Access class constant and static method from string

I have a string containing the class name and I wish to get a constant and call a (static) method from that class.

JavaScript

As I expected (more or less), using $variable::CONSTANT or $variable::method(); doesn’t work.

Before asking what I have tried; I’ve tried so many things I basically forgot.

What’s the best approach to do this? Thanks in advance.

Advertisement

Answer

To access the constant, use constant():

JavaScript

Be advised: If you are working with namespaces, you need to specifically add your namespace to the string even if you call constant() from the same namespace!

For the call, you’ll have to use call_user_func():

JavaScript

However: this is all not very efficient, so you might want to take another look at your object hierarchy design. There might be a better way to achieve the desired result, using inheritance etc.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement