CarlosCarucce CarlosCarucce - 6 months ago 14
PHP Question

TypeHinting for attrubutes in php7?

Does php 7 support type hinting for class attributes?

I mean, not just for setters/getters but for the attribute itself. Something like:

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

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

Answer

PHP 7.0, which is the current minor release at the time of writing (2016-05-16), does not support this. That said, there is some work in that direction, e.g. the Typed Properties RFC, which may end up in PHP 7.1.


In the meantime, 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.

Comments