Home > Net >  Finding out the type from an uninitialized typed property
Finding out the type from an uninitialized typed property

Time:10-16

I have the following code in my User class:

class User {
    
    public int $id = 0;
    public string $code;
    public string $name;
}

When assigning $code from the database, I need to find out what type the var is before I can assign it, so I use gettype(), in the __construct function for User:

foreach($data as $key => $val) {
    settype($val, gettype($this->$key));
    $this->$key = $val;
}

However it returns this error:

Fatal error: Uncaught Error: Typed property User::$code must not be accessed before initialization

I understand what the error message means.

Is there a way to find out the casted type of the variable before its been set?

CodePudding user response:

I'm not sure what exactly you are attempting to do, and without knowing more about the whole thing I won't risk an opinion about the logic of it.

Putting that aside, using gettype() on an uninitialized typed property won't work, because the property has effectively no value at that point.

But, since the property is typed, you could get the property defined type via reflection:

class User {
    
    public int $id = 0;
    public string $code;
    public string $name;
    
    public function __construct() {
        
        $reflect = new ReflectionClass($this);
        $props   = $reflect->getProperties();
        foreach ($props as $prop) {
            echo $prop->getType()->getName(), "\n";            
        }

    }
}

new User();

The above would enter image description here

It gives a warning and evaluates to true, so the uninitialized variable was indeed null.

Since yivi pointed out that the question refers to a property, I have conducted another experiment:

<?php

class Foo {
        public $foo;
        public function __construct() {
            echo var_dump($this->foo === null);
        }
}

new Foo();

and the result is

enter image description here

  • Related