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
Typed properties include modifiers ( private , protected , and public ) and types (except void and callable ). Typed properties have uninitialized states, not null like untyped properties.
Type hinting is a concept that provides hints to function for the expected data type of arguments. For example, If we want to add an integer while writing the add function, we had mentioned the data type (integer in this case) of the parameter.
Apparently 'type hinting' in PHP can be defined as follows: "Type hinting" forces you to only pass objects of a particular type. This prevents you from passing incompatible values, and creates a standard if you're working with a team etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With