Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP class declaration

Tags:

php

Is there any way to set explicit type to object field in php? Something like this

class House{
       private Roof $roof
}
like image 648
Ris90 Avatar asked Jun 16 '10 22:06

Ris90


People also ask

How do you declare a class in PHP?

Define a class with keyword “class” followed by name of the class. Define the constructor method using “__construct” followed by arguments. The object of the class can then be instantiated using “new ClassName( arguments_list )” Define class variables.

Can you create a class in PHP?

Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values. Objects of a class is created using the new keyword.

What does :: class do in PHP?

SomeClass::class will return the fully qualified name of SomeClass including the namespace. This feature was implemented in PHP 5.5. It's very useful for 2 reasons. You can use the use keyword to resolve your class and you don't need to write the full class name.


2 Answers

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;
}
like image 151
JW. Avatar answered Oct 02 '22 11:10

JW.


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.

like image 20
Bill Karwin Avatar answered Oct 02 '22 11:10

Bill Karwin