How can I access an object property named as a variable in php?

前端 未结 5 1683
陌清茗
陌清茗 2020-12-04 16:04

A Google APIs encoded in JSON returned an object such as this

[updated] => stdClass Object
(
 [$t] => 2010-08-18T19:17:42.026Z
)

Anyone

相关标签:
5条回答
  • 2020-12-04 16:30

    I'm using php7 and the following works fine for me:

    class User {
        public $name = 'john';
    }
    $u = new User();
    
    $attr = 'name';
    print $u->$attr;
    
    0 讨论(0)
  • 2020-12-04 16:36

    Have you tried:

    $t = '$t'; // Single quotes are important.
    $object->$t;
    
    0 讨论(0)
  • Since the name of your property is the string '$t', you can access it like this:

    echo $object->{'$t'};
    

    Alternatively, you can put the name of the property in a variable and use it like this:

    $property_name = '$t';
    echo $object->$property_name;
    

    You can see both of these in action on repl.it: https://repl.it/@jrunning/SpiritedTroubledWorkspace

    0 讨论(0)
  • 2020-12-04 16:46

    Correct answer (also for PHP7) is:

    $obj->{$field}
    
    0 讨论(0)
  • 2020-12-04 16:48

    this works on php 5 and 7

    $props=get_object_vars($object);
    echo $props[$t];
    
    0 讨论(0)
提交回复
热议问题