Does php 7 support type hinting for class properties?
I mean, not just for setters/getters but for the property itself.
Something like:
Edit for PHP 7.4 :
Since PHP 7.4 you can type attributes (Documentation / Wiki) which means you can do :
class Foo
{
protected ?Bar $bar;
public int $id;
...
}
According to wiki, all acceptable values are :
PHP < 7.4
It is actually not possible and you only have 4 ways to actually simulate it :
I combined all of them here
class Foo
{
/**
* @var Bar
*/
protected $bar = null;
/**
* Foo constructor
* @param Bar $bar
**/
public function __construct(Bar $bar = null){
$this->bar = $bar;
}
/**
* @return Bar
*/
public function getBar() : ?Bar{
return $this->bar;
}
/**
* @param Bar $bar
*/
public function setBar(Bar $bar) {
$this->bar = $bar;
}
}
Note that you actually can type the return as ?Bar since php 7.1 (nullable) because it could be null (not available in php7.0.)
You also can type the return as void since php7.1