John Stamoutsos
John Stamoutsos

Reputation: 191

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.

Upvotes: 1

Views: 751

Answers (3)

Alain
Alain

Reputation: 36964

You should be careful with the PHP version you're using.

In PHP 7.1, \ReflectionParameter::getType() returns an instance of ReflectionNamedType or null:

public function hello(Foo $bar);

In PHP 8.0, \ReflectionParameter::getType() may also return an instance of ReflectionUnionType.

public function hello(Foo|Bar $baz);

In PHP 8.1, \ReflectionParameter::getType() may also return an instance of \ReflectionIntersectionType.

public function hello(Foo&Bar $baz);

So in recent PHP versions, you cannot only support a single class FQDN (the fully qualified class name).

To give an implementation example, in a Symfony project, you may know whether a \ReflectionType is an entity using the following code:

private function isEntity(\ReflectionNamedType|\ReflectionUnionType|\ReflectionIntersectionType|null $type): bool
{
    if (null === $type) {
        return false;
    }

    if ($type instanceof \ReflectionNamedType && str_contains($type->getName(), '\\Entity\\')) {
        return true;
    }

    if ($type instanceof \ReflectionUnionType || $type instanceof \ReflectionIntersectionType) {
        foreach ($type->getTypes() as $subType) {
            if ($this->isEntity($subType)) {
                return true;
            }
        }
    }

    return false;
}

(This code is used in a unit test that checks whether resources received in symfony controllers are well protected using #[IsGranted] attributes, you can check its full code here).

Upvotes: 1

Narf
Narf

Reputation: 14752

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.

Upvotes: 3

ailok
ailok

Reputation: 56

If I understand you correctly you need to get class name with namespace... In PHP namespace is part of class name. And there is simple build-in function get_class($object).

Upvotes: 0

Related Questions