Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 671
CarlosCarucce Avatar asked May 16 '16 13:05

CarlosCarucce


People also ask

What are typed properties PHP?

Typed properties include modifiers ( private , protected , and public ) and types (except void and callable ). Typed properties have uninitialized states, not null like untyped properties.

What is type hinting in PHP with example?

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.

Should I use type hinting in PHP?

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.


1 Answers

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.

like image 149
Andrea Avatar answered Oct 07 '22 13:10

Andrea