Access class constant and static method from string

You can achieve it by setting a temporary variable. Not the most elegant way but it works.

public function runMethod() {
    // Temporary variable
    $myclass = $this->myclass;
    // Get the selected constant here
    print $myclass::CONSTANT;

    // Call the selected method here
    return $myclass::method('input string');
}

I guess it's to do with the ambiguity of the ::, at least that what the error message is hinting at (PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM)


To access the constant, use constant():

constant( $this->myClass.'::CONSTANT' );

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():

call_user_func( array( $this->myclass, 'method' ) );

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.


Use call_user_func to call static method:

call_user_func(array($className, $methodName), $parameter);

in php 7 you can use this code

echo 'my class name'::$b;

or

#Uncomment this lines if you're the input($className and $constName) is safe.
$reg = '/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/';
if(preg_match($reg,$className) !== 1 || preg_match($reg,$constName) !== 1)
    throw new \Exception('Oh, is it an attack?');
$value = eval("return $className::$constName;");