Kris_Stoltz
Kris_Stoltz

Reputation: 948

How to return expected data type in PHP

I need to save the expected type to a variable. I have a class and the class has a property, this is the property:

public ?DateTime $start = null;

How can I access the expected data type (in this case a DateTime object)?

Upvotes: 0

Views: 209

Answers (1)

Álvaro González
Álvaro González

Reputation: 146390

You can use reflection:

class Test
{
    public ?DateTime $start = null;
}

$rp = new ReflectionProperty(Test::class, 'start');
echo $rp->getType()->getName(), "\n";
echo $rp->getType()->allowsNull() ? 'nullable' : 'not nullable';

Demo

Upvotes: 2

Related Questions