phpattributesphp-7type-hintingvariable-types

Type hinting for properties in PHP 7?


Does php 7 support type hinting for class properties?

I mean, not just for setters/getters but for the property itself.

Something like:

class Foo {
    /**
     *
     * @var Bar
     */
    public $bar : Bar;
}

$fooInstance = new Foo();
$fooInstance->bar = new NotBar(); //Error

Solution

  • PHP 7.4 will support typed properties like so:

    class Person
    {
        public string $name;
        public DateTimeImmutable $dateOfBirth;
    }
    

    PHP 7.3 and earlier do not support this, but there are some alternatives.

    You can make a private property which is accessible only through getters and setters which have type declarations:

    class Person
    {
        private $name;
        public function getName(): string {
            return $this->name;
        }
        public function setName(string $newName) {
            $this->name = $newName;
        }
    }
    

    You can also make a public property and use a docblock to provide type information to people reading the code and using an IDE, but this provides no runtime type-checking:

    class Person
    {
        /**
          * @var string
          */
        public $name;
    }
    

    And indeed, you can combine getters and setters and a docblock.

    If you're more adventurous, you could make a fake property with the __get, __set, __isset and __unset magic methods, and check the types yourself. I'm not sure if I'd recommend it, though.