Reputation: 12213
I have a base class that has several classes that inherit from it.
class Pet{
...
}
class Dog extends Pet{
...
}
class Cat extends Pet{
...
}
Then I have another class that consumes this class
class Person{
/** @var Pet */
public $pet;
}
These classes are based on some JSON object I will receive. The JSON object could contain a Dog object, or a Cat object. I run a switch
statement to figure out which it is at runtime and handle it appropriately. However I would like to have type hinting via PHPDoc for whether it's a cat or dog. I have been unable to figure out how to specify at runtime that it's type has changed from a Pet
to a Dog
. This didn't work - it still just thinks it's a plain old Pet
object.
$pet = json_decode($jsonObj);
if($pet->type == "dog"){
/** @var Dog */
$pet = $pet;
}
Any idea how to change the type to a sub-type at runtime with PHPDoc?
Upvotes: 0
Views: 531
Reputation: 43574
You can use the following using instanceof
:
if ($pet instanceof Dog) {
$dog = $pet;
//now the IDE and runtime knows it is a Dog.
} elseif ($pet instanceof Cat) {
$cat = $pet;
//now the IDE and runtime knows it is a Cat.
}
Another way only using the DocBlock:
if ($pet->type === "dog") {
/** @var Dog $dog */
$dog = $pet;
//now the IDE knows it is a Dog (at runtime this could be a Cat too).
} elseif ($pet->type === "cat") {
/** @var Cat $cat */
$cat = $pet;
//now the IDE knows it is a Cat (at runtime this could be a Dog too).
}
Upvotes: 2