Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPStorm and magic methods

I am using PHPStorm and have written a class that utilises the SimpleXML class. Everything is fine, except when I traverse an XML string I will get "Undefined Property" warnings.

$xml = simplexml_load_string($string); //Returns SimpleXML Element

echo $xml->childElement; //PHPStorm reports "Undefined Property

I believe this is because the magic properties are not properly defined in PHPStorm. Is anyone aware of a nice little work around? It annoys me because I am pedantic about having nice clean code (and IDE) and having warnings come up on a class is just awful!

like image 219
Sam Williams Avatar asked Mar 12 '12 11:03

Sam Williams


1 Answers

I have not found a work-around so far but just creating a type with the properties in question and var-type-hinting the variable:

class myXmlStoredValueObject {
     /* @var string */
     public $childElement;
}

$xml = simplexml_load_string($string); //Returns SimpleXML Element

/* @var $xml myXmlStoredValueObject */

echo $xml->childElement;

Naturally this is not always applicable / practicable, there is a cheat with stdClass:

$xml = simplexml_load_string($string); //Returns SimpleXML Element

/* @var $xml stdClass */

echo $xml->childElement;

You don't need to declare any concrete type to make the hint disappear.

There are other deficiencies, too, you will still run into issues withforeach e.g., where you need to var-type-hint again.

like image 169
hakre Avatar answered Oct 02 '22 06:10

hakre