简体   繁体   中英

PHP OOP DocBlock @var for $this->var

A class "DerivedClass" extends "BaseClass". It instantiates an object of type ProcessDerived, passing $this to the constructor:

$object = new ProcessDerived($this); // $this extends BaseClass

A series of DerivedX classes have their own ProcessDerivedX classes, and all ProcessDerivedX classes are derived from ProcessBase. To keep the code more generic the ProcessDerivedX classes have a constructor that accepts any BaseClass.

/**
 * Constructor accepts object of type BaseClass
 *
 * @param BaseClass $parent
 */
function __construct($parent) { $this->parent = $parent; }

This allows Intellisense to detect issues with references like:

$result = $this->parent->baseFunction();

Since $this->parent is of type BaseClass, we know baseFunction must be present in any DerivedClassX.

But when we specifically intend to use a function of DerivedClassX in ProcessClassX, we expect $this->parent to be DerivedClassX, with functions that are not defined in BaseClass.

So the question is, how do we annotate such a reference so that Intellisense, debugging, etc recognizes baseFunction() ?

Example:

/** @var DerivedClassX $this->parent Specific to derived class */
$result1 = $this->parent->uniqueFunction();

/** @var BaseClass $this->parent Specific to base class */
$result2 = $this->parent->baseFunction();

The above syntax for $this->parent doesn't work. I'm looking for syntax that does work. :)

A workaround to this problem is to simplify the syntax. I don't like this but for now this is what I'm doing.

$the_parent = $this->parent;
/** @var DerivedClassX $the_parent */
$result1 = $the_parent->uniqueFunction();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM