0

Following situation:

foreach ($this->allEvents as $event) {
    //use $event here
}

allEvents (array) stores several objects of Event class. Now I want that my IDE (PhpStorm) suggests me all methods that $event has. But unfortunately is does not know that $event is a Event object.

Is there any possibility to convert $event to an object of Event class? Like type conversions in Java: (Event) event

4
  • What does $this->allEvents look like? Commented Aug 22, 2018 at 20:24
  • 2
    The problem probably lies somewhere in the way you annotated the property allEvents in your class. If you properly annotated allEvents or have a proper getter that has return annotations it should work. Make sure you are not just dynamically declaring the property because PHPStorm can't know whats going on then. Commented Aug 22, 2018 at 20:24
  • @Xatenev oh my gosh... I got it. I annotated it with (@ var array Event) but the proper version is @ var Event[]. Thank you so much :) Commented Aug 22, 2018 at 20:32
  • In Eclipse you can do \*@var $var Object*/ just before the foreach. Not sure if PhpStorm has a similar method. Commented Aug 22, 2018 at 22:05

2 Answers 2

2

Thanks to @Xatenev The problem was a wrong annotation of $allEvents. It has to look like

/**
 * @var Event[]
 */
private $allEvents = array();

so PhpStorm will understand it correctly as an array of Event objects

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

Comments

0

Alternatively you can use assert inside foreach to make your IDE aware of the type of the variable:

foreach ($this->allEvents as $event) {
    assert($event instanceof Event);
    //use $event here
}

Assertions are not executed in the production code so there is no additional overhead of using them.

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.