【问题标题】:How to properly typehint SimpleXMLElement?如何正确输入 SimpleXMLElement?
【发布时间】:2015-11-29 01:45:21
【问题描述】:

有没有办法正确输入 \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 类型提示?

【问题讨论】:

    标签: php simplexml phpstorm type-hinting


    【解决方案1】:

    如果您在 PHPStorm 中按住 Ctrl 键单击 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 是一个 hack,用于阻止该方法显示在自动完成结果中,因为您实际上无法在真正的 PHP 代码中调用 $node->__get()$node->offsetGet()。)

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 2020-10-09
      • 1970-01-01
      • 2020-09-17
      • 2021-09-28
      • 2021-01-26
      • 2018-11-14
      • 2019-12-19
      • 2020-07-08
      相关资源
      最近更新 更多