【问题标题】:How to instantiate stdClass in place如何就地实例化stdClass
【发布时间】:2010-12-11 08:26:39
【问题描述】:

是否可以在php中做到这一点?

Javascript 代码:

var a = {name: "john", age: 13}; //a.name = "john"; a.age = 13

即时实例化 stdClass 变量?

【问题讨论】:

    标签: php javascript code-snippets stdclass


    【解决方案1】:

    尝试使用关联数组语法,并转换为object:

    $a = (object)array('name' => 'john', 'age' => 13);
    echo $a->name; // 'john'
    

    【讨论】:

    • 铸造似乎是最好的方法,但我认为你将它投射到 (object) 而不是 (stdClass) 根据 php.net/manual/en/language.types.type-juggling.php
    • @adam:没错。 stdClass 曾经工作过吗?在我的脑海中,它曾经确实有效。
    • 我认为 php 总是将对象报告为 stdClass(带有 var_dump 等),但实际类型是对象。如果你问我,两个方向应该是一样的。
    【解决方案2】:

    你也可以这样做:

    $a = new stdClass;
    $a->name = 'john';
    $a->age = 13;
    

    【讨论】:

      【解决方案3】:

      另一种方式:

      $text = '{"name": "john", "age": 13}';
      $obj = json_decode($text);
      

      【讨论】:

      • 比将数组转换为对象需要更多的处理。
      猜你喜欢
      • 2021-08-11
      • 2011-10-12
      • 2017-07-07
      • 1970-01-01
      • 2010-12-02
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多