0

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?

1 Answer 1

2

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).

}
Sign up to request clarification or add additional context in comments.

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.