json_decode-d 对象的 PHP 文档块

问题描述

我从 PHP 代码中的 JSON 字符串获取对象。我希望我的 IDE (NetBeans) 知道对象的参数,而无需为它们创建特殊的类。

我可以吗?

它看起来像:

$obj = json_decode($string);
/** 
 * @var $obj { 
 *     @property int    $id
 *     @property string $label
 * } 
*/

解决方法

当我使用 PHP 7 时,我可以定义匿名类。

所以,我的解决方案是:

        $obj = (new class {

                /**
                 * @property int $id 
                 */
                public /** @var string */ $label;

                public function load(string $string): self
                {
                    $data = json_decode($string,true);
                    foreach ($data as $key => $value) {
                        $this->{$key} = $value;
                    }                        
                    
                    return $this;
                }
            })->load($string);


        echo $obj->id;
        echo $obj->label;

我认为这是一道很棒的意大利面。

,

这是它的结构化版本

首先,您在 helpers 文件夹中的某处创建一个类

<?php

namespace App\Helpers;

use function json_decode;

class JsonDecoder
{


    public function loadString(string $string): self
    {
        $array = json_decode($string,true);

        return $this->loadArray($array);
    }


    public function loadArray(array $array): self
    {
        foreach ($array as $key => $value) {
            $this->{$key} = $value;
        }

        return $this;
    }


}

那么,你要小心使用它

        $obj= (new class() extends JsonDecoder {
                public /** @var int     */ $id;
                public /** @var string  */ $label;
            });
        $obj->loadString($string);

        echo $obj->id;
        echo $obj->label;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...