Ris90
Ris90

Reputation: 841

PHP class declaration

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

class House{
       private Roof $roof
}

Upvotes: 5

Views: 2878

Answers (5)

Andreas Linden
Andreas Linden

Reputation: 12721

you could also use the following before using the member

if (!$this->roof instanceof Roof) {

    throw new Exception('$this->roof is not an instance of Roof');
}

Upvotes: 0

Bill Karwin
Bill Karwin

Reputation: 562310

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.

Upvotes: 9

CaseySoftware
CaseySoftware

Reputation: 3125

You're looking for PHP's Type Hinting. It works great on function/method calls. Here's the manual:

http://php.net/manual/en/language.oop5.typehinting.php

Upvotes: 3

Jake Kalstad
Jake Kalstad

Reputation: 2065

Why not just assign $roof to a new Roof()?

Upvotes: 0

JW.
JW.

Reputation: 51638

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;
}

Upvotes: 10

Related Questions