更改变量类型phpDoc

时间:2017-12-14 17:48:12

标签: php phpdoc

我有一个基类,它有几个继承它的类。

class Pet{
  ...
}
class Dog extends Pet{
   ...
}
class Cat extends Pet{
   ...
}

然后我有另一个消耗这个类的课程

class Person{
   /** @var Pet */
   public $pet;
}

这些类基于我将收到的一些JSON对象。 JSON对象可以包含Dog对象或Cat对象。我运行switch语句来确定它在运行时是什么并适当地处理它。但是,我希望通过PHPDoc进行类型提示,无论是猫还是狗。我一直无法弄清楚如何在运行时指定它的类型已从Pet更改为Dog。这不起作用 - 它仍然只是认为它是一个普通的Pet对象。

$pet = json_decode($jsonObj);
if($pet->type == "dog"){
   /** @var Dog */
   $pet = $pet;
}

知道如何使用PHPDoc在运行时将类型更改为子类型吗?

1 个答案:

答案 0 :(得分:1)

您可以使用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.
}

仅使用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).

}