我有同样的问题,所以我写了一个packagist来解决它,这是给你的礼物。
https://packagist.org/packages/stark641/stark-object
https://github.com/stark641/stark-object
- 您可以从 json 生成 PHP 类文件
./vendor/bin/stark-object-gen --path=/tmp --json='{"foo_bar":{"foo":1.3,"bar":[641,641]}}'
output
Class FooBar saved at: /tmp/FooBar.php
Class BaseClass saved at: /tmp/BaseClass.php
- 您可以将 json 映射到 php 对象
class FooBarClass extends StarkObject
{
/** @var string */
public $foo;
/** @var integer */
public $bar;
}
class DemoClass extends StarkObject
{
/** @var FooBarClass */
public $foobar;
/** @var FooBarClass[] */
public $foobars;
}
$json = '{"foobar":{"foo":"hello world","bar":64100},"foobars":[{"foo":"hello","bar":641},{"foo":"world","bar":664411}]}';
$demo = (new DemoClass())->fromJson($json);
var_export($demo);