Search code examples
phpphp-8

How to get union types of a class property when using ReflectionProperty?


I am trying to get the union types of a property on a class using ReflectionProperty. But having no luck.

class Document 
{
   // Standard type
   public string $companyTitleStandard;

   // Union types
   public DocumentFieldCompanyTitle|string $companyTitleUnion;
}

Standard type works fine. Union types however, I cannot for love nor money figure out how to implement.

$rp = new ReflectionProperty(Document::class, 'companyTitleStandard');
echo $rp->getType()->getName(); // string

$rp = new ReflectionProperty(Document::class, 'companyTitleUnion');
echo $rp->getTypes(); // Exception: undefined method ReflectionProperty::getTypes()    
echo $rp->getType()->getTypes(); // Exception: undefined method ReflectionNamedType::getTypes()

I'm ultimately looking for something like this to play with:

['DocumentFieldCompanyTitle', 'string']

Any ideas anyone? Thanks in advance


Solution

  • On union types, the first

    $rp->getType()
    

    will return a ReflectionUnionType.
    To get the names of the individual types in the union, you then need to iterate through

    $rp->getType()->getTypes()
    

    So to just output the types:

    foreach ($rp->getType()->getTypes() as $type) {
        echo $type->getName() . PHP_EOL;
    }
    

    If you rather get the types for union in a normal array, you can do this:

    $unionTypes = array_map(function($type) { 
        return $type->getName();
    }, $rp->getType()->getTypes());
    

    Or for short in a one-liner:

    $unionTypes = array_map(fn($type) => $type->getName(), $rp->getType()->getTypes());
    

    Here's a demo: https://3v4l.org/SlbXX#v8.0.19