Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you access the properties of an object with a variable?

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] .

How do you access the properties of an object in PHP?

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 .

How do you access the dynamic property of an object?

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] .

How do you declare an object variable in PHP?

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];