Is there any way to set explicit type to object field in php? Something like this
class House{
private Roof $roof
}
Nope, there isn't. PHP variables can always be of any type. But you can enforce a type in the setter:
public function setRoof(Roof $roof) {
$this->roof = $roof;
}
bool for example, you could always assert('is_bool($value)');.You can't use PHP code to declare the type of an object field.
But you can put type hints in docblock comments:
class House{
/**
* @var Roof
*/
private $roof
}
This still doesn't make the code enforce types, but some IDE tools understand the docblocks and may warn you if you use this variable without conforming to the type hint.
You're looking for PHP's Type Hinting. It works great on function/method calls. Here's the manual: