Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .
Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .
To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .
The object variable is declared by using the new keyword followed by the class name. Multiple object variables can be declared for a class. The object variables are work as a reference variable.
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
Correct answer (also for PHP7) is:
$obj->{$field}
Have you tried:
$t = '$t'; // Single quotes are important.
$object->$t;
I'm using php7 and the following works fine for me:
class User {
public $name = 'john';
}
$u = new User();
$attr = 'name';
print $u->$attr;
this works on php 5 and 7
$props=get_object_vars($object);
echo $props[$t];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With