Answer the question
In order to leave comments, you need to log in
How to document the type of a variable in a derived class in PHP?
Good afternoon!
Faced the following problem.
There is a parent class, for example IterableCollection - an iterator that implements the Iterator interface. This class has the $items property, which is an array of some elements (for the IterableCollection class, it does not matter what these elements are).
class IterableCollection implements \Iterator
{
/**
* @var mixed[]
*/
protected $items = [];
...
}
class SomeCollection extends IterableCollection
{
public function doSomeWork()
{
$this->items[0]->someMethod();
}
...
}
/**
* @var mixed[]
*/
protected $items = [];
}
/**
* @var array
*/
protected $items = [];
}
/**
* @property SomeClass[] $items
*/
class SomeCollection extends IterableCollection {
...
}
Answer the question
In order to leave comments, you need to log in
Obviously, in the absence of generic programming tools (generics) in PHP, it is impossible to do this without crutches (copying code, copying phpDocs, assigning the $items property to magic and public ones, etc.).
class SomeCollection extends IterableCollection
{
/**
* @var SomeClass[] $items
*/
...
public function doSomeWork()
{
$this->items[0]->someMethod();
}
...
}
Very sudden indeed :)
/**
* @var mixed[]
*/
protected $items = [];
/**
* @property SomeClass[] $items
*/
class SomeCollection extends IterableCollection
// ...
public function doSomeWork()
{
/** @var SomeClass[] $items */
$items = $this->items;
$items[0]->someMethod();
}
/**
* @return SomeClass[]
*/
protected function getItems ()
{
return $this->items;
}
public function doSomeWork()
{
$this->getItems()[0]->someMethod();
}
another option with re-defining the property with the correct phpDoc
class SomeCollection extends IterableCollection
{
/**
* @var SomeClass[]
*/
protected $items = [];
public function doSomeWork()
{
$this->items[0]->someMethod();
}
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question