json - PHP docblock for json_decode-d objects

I'm getting objects from JSON string in my PHP code. I want my IDE (NetBeans) to know the parameters of the objects without creating special class for them.
Can I do it?
It would look something like:
$obj = json_decode($string);
/**
* @var $obj {
* @property int $id
* @property string $label
* }
*/
Answer
Solution:
As I'm using PHP 7 I can define anonymous class.
So, my solution was:
$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;
I think it is an amazing spaghetti dish.
Answer
Solution:
Here is a structured version for it
first, you make a class somewhere in yourhelpers
folder
<?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;
}
}
then, you use it with care
$obj= (new class() extends JsonDecoder {
public /** @var int */ $id;
public /** @var string */ $label;
});
$obj->loadString($string);
echo $obj->id;
echo $obj->label;
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to undefined function illuminate\encryption\openssl_cipher_iv_length()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.