PHP替代编写stdClass的方法

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

在PHP中执行stdClass时我们可以这样做:

// Create new stdClass Object
$init = new stdClass;

// Add some test data
$init->foo = "Test data";
$init->bar = new stdClass;
$init->bar->baaz = "Testing";
$init->bar->fooz = new stdClass;
$init->bar->fooz->baz = "Testing again";
$init->foox = "Just test";

有没有其他替代方法可以使它看起来更像我们可以使用JavaScript?

谢谢。

php stdclass
2个回答
5
投票
$array  = array('x'=>123);
$object = (object) $array;

0
投票

我不知道它是否更干净,从PHP7开始,你可以使用anonymous classes,但是:

$init = new class {};

var_dump($init);
/*
object(class@anonymous)#1 (0) {
}
*/

}

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