5

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

class House{
       private Roof $roof
}

5 Answers 5

10

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Note that you can only enforce objects or arrays, but not "primitive" types like float or string.
Had you a setter that expected a primitive type, bool for example, you could always assert('is_bool($value)');.
@svens: FWIW, PHP development added scalar type hinting on 5/20/2010. I'm not sure when that will make it into an official release, though.
9

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.

Comments

3

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.