Search code examples
phpparametersnamespaces

PHP How can get the namespace of class method parameter?


Hello i try many things to catch the namespace of an parameter function but nothing.

public function table(Homes $homes) { // <---------- Homes
    return $homes->get('home');
}

I try with ReflectionClass but give me only the name $homes not the Homes namespace.


Solution

  • It's possible:

    $method         = new ReflectionMethod('classDeclaringMethodTable', 'table');
    
    // ReflectionMethod::getParameters() returns an *array*
    // of ReflectionParameter instances; get the first one
    $parameter      = $declaringMethod->getParameters()[0];
    
    // Get a ReflectionClass instance for the parameter hint
    $parameterClass = $parameter->getClass();
    

    And then at this point, it depends on exactly what you want ...

    // Returns ONLY the namespace under which class Homes was declared
    $parameterClass->getNamespaceName();
    
    // Returns the fully qualified class name of Homes
    // (i.e. namespace + original name; it may've been aliased)
    $parameterClass->getName();
    

    I've used multiple variables to make it easier to follow, but it can easily be a one-liner with method chaining.