如何正确键入SimpleXMLElement?

问题描述 投票:1回答:1

有没有办法正确键入一个\ SimpleXMLElement?所以我不必键入所有它访问的内容也是一个\ SimpleXMLElement?

如果我想要一直打字,我现在必须这样做:

   /**
     * @var \SimpleXMLElement $values (this is not! an array, yet it is traversable)
     */
    $values = $response->params->param->value->array->data->value;
    foreach ($values as $row) {
        $row = $row->array->data->value;

        /**
         * @var \SimpleXMLElement $row
         */

        $entry = $row[0];

        /**
         * @var \SimpleXMLElement $entry
         */
        $xmlString = $entry->asXML();
}

这看起来非常冗长和多余。有没有办法键入一个SimpleXMLElement,以便它返回的所有内容也将是coreclty typehinted?

php simplexml phpstorm type-hinting
1个回答
4
投票

如果按住Ctrl键单击并转到PHPStorm中SimpleXMLElement的“定义”,您将看到它有一个存根类定义,用于自动完成和代码分析。

在较旧版本的PHPStorm中,重载的->运算符在该存根中表示如下(取自PHPStorm 9.0):

/**
 * Provides access to element's children
 * @param $name child name
 * @return SimpleXMLElement[]
 */
function __get($name) {}

注意,这里的返回类型是SimpleXMLElement[],即“SimpleXMLElement对象的数组”。如果你写一些类似$node->childName[0]->grandChild[0]->asXML()的话,它允许它正确地自动完成,但是如果你使用$node->childName->grandChild->asXML()的简写形式则不能

这可能被归类为IDE中的一个错误,并且是filed in their public tracker as WI-15760,现在已修复。

从PHPStorm 2018.1.2开始,存根改为将__get()的返回类型声明为SimpleXMLElement,并且还声明implements ArrayAccessoffsetGet()也返回SimpleXMLElement

/**
 * Provides access to element's children
 * @access private Method not callable directly, stub exists for typehint only
 * @param string $name child name
 * @return SimpleXMLElement
 */
private function __get($name) {}

/**
 * Class provides access to children by position, and attributes by name
 * @access private Method not callable directly, stub exists for typehint only
 * @param string|int $offset
 * @return SimpleXMLElement Either a named attribute or an element from a list of children
 */
private function offsetGet ($offset) {}

这应该正确地自动完成显式[0]和短手情况。

@access private是一个黑客,可以阻止显示自动完成结果的方法,因为你实际上无法在真正的PHP代码中调用$node->__get()$node->offsetGet()。)

© www.soinside.com 2019 - 2024. All rights reserved.