Problem
In PHP, how can I get a property based on a string? I’m going to call it magic. So, what exactly is magic?
$obj->Name = 'something';
$get = $obj->Name;
would be like…
magic($obj, 'Name', 'something');
$get = magic($obj, 'Name');
Asked by Daniel A. White
Solution #1
Like this
<?php
$prop = 'Name';
echo $obj->$prop;
If you have control over the class, you can simply implement the ArrayAccess interface and perform this.
echo $obj['Name'];
Answered by Peter Bailey
Solution #2
Use the notation: to access the property without having to create an intermediate variable.
$something = $object->{'something'};
This also allows you to construct the property name in a loop, such as:
for ($i = 0; $i < 5; $i++) {
$something = $object->{'something' . $i};
// ...
}
Answered by laurent
Solution #3
Variable Variables is the term for what you’re asking about. All you have to do is save your string in a variable and use it as follows:
$Class = 'MyCustomClass';
$Property = 'Name';
$List = array('Name');
$Object = new $Class();
// All of these will echo the same property
echo $Object->$Property; // Evaluates to $Object->Name
echo $Object->{$List[0]}; // Use if your variable is in an array
Answered by matpie
Solution #4
Something along these lines? I haven’t tried it yet, but it should be fine.
function magic($obj, $var, $value = NULL)
{
if($value == NULL)
{
return $obj->$var;
}
else
{
$obj->$var = $value;
}
}
Answered by Ólafur Waage
Solution #5
Simply save the property name in a variable and access the property using the variable. As an example:
$name = 'Name';
$obj->$name = 'something';
$get = $obj->$name;
Answered by Jon Benedicto
Post is based on https://stackoverflow.com/questions/804850/get-php-class-property-by-string