在JavaScript中,你可以通过以下方法轻松创建一个没有类的对象:

 myObj = {};
 myObj.abc = "aaaa";

对于PHP,我找到了这个,但它已经有将近4年的历史了: http://www.subclosure.com/php-creating-anonymous-objects-on-the-fly.html

$obj = (object) array('foo' => 'bar', 'property' => 'value');

现在在2013年的PHP 5.4中,是否有替代方案?


当前回答

你总是可以使用new stdClass()。示例代码:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

同样,在PHP 5.4中,你可以得到相同的输出:

$object = (object) ['property' => 'Here we go'];

其他回答

你总是可以使用new stdClass()。示例代码:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

同样,在PHP 5.4中,你可以得到相同的输出:

$object = (object) ['property' => 'Here we go'];