Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading