phpsyntaxsyntax-errorlate-static-binding

Why can't I directly use function return values as dynamic class names in PHP?


As of PHP 5.3, it is possible to use a variable as a class name, not only for object instantiation but even for static methods as well:

$className = 'My\Name\Spaced\Thing';
$thing = $className::foo('hello world');

However, if I try to use the return value of a function or method instead of an actual variable, I get an error:

function getClassName() 
{
    return 'My\Name\Spaced\Thing';
}

// Raises "syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)"
$thing = getClassName()::foo('hello world');

This, on the other hand, works just fine:

$className = getClassName();
$thing = $className::foo('hello world');

What gives? Did I just find a bug in PHP's (5.6) syntax processor?


Solution

  • I don't know if I'd call it a "bug," but it's certainly an idiosyncrasy of PHP prior to PHP 7. This, and a whole class of similar issues, was addressed by the Uniform Variable Syntax RFC.