Okay, Lets say I have an object with properties like this:
$testObj->wind->windi // this returns a value like 100 mph
$testObj->wind->windii // this returns a value like 110 mph
I need to access a property but I don't know what property explicitly, Instead I have a string like this:
$str = 'wind->windii';
Calling predefined values works:
echo $testObj->wind->windii; //results in 110 mph
The Problem: I need a way to get the values without hard coding the actual properties:
echo $testObj->$str; //and have it result in 110 mph
I thought this was a variable variables situation but I had no luck getting that to work and after a few hours of frustration I'm asking for help
*edit: I also need to mention that the object name changes as well so we can't hard code $testObj but rather be able to take any object and any string and get it's properties
Also, bracket notation isn't working, it results in "Undefined property: stdClass::$wind->elevation"
For those following at home, this is the var_dump of $testObj
object(stdClass)#299 (2) {
["snow"]=>
object(stdClass)#315 (3) {
["elevation"]=>
string(5) "365.4"
["results"]=>
string(1) "6"
["status"]=>
int(1)
}
["wind"]=>
object(stdClass)#314 (5) {
["elevation"]=>
string(5) "365.4"
["windi"]=>
string(7) "100 mph"
["windii"]=>
string(7) "110 mph"
["windiii"]=>
string(7) "115 mph"
["status"]=>
int(1)
}
}
Finally I have working code.
With mental support from @NigelRen
Emotional support from @FunkFortyNiner
And most of the code from this question about arrays
Test Object:
$obj = json_decode('{"snow":{"elevation":"365.4","results":"6","status":1},"wind":{"elevation":"365.4","windi":"100 mph","windii":"110 mph","windiii":"115 mph","status":1}}');
Test Directory:
$path = 'wind:windii';
Getter:
function get($path, $obj) {
$path = explode(':', $path);
$temp =& $obj;
foreach($path as $key) {
$temp =& $temp->{$key};
}
return $temp;
}
var_dump(get($path, $obj)); //dump to see the result
Setter:
function set($path, &$obj, $value=null) {
$path = explode(':', $path);
$temp =& $obj;
foreach($path as $key) {
$temp =& $temp->{$key};
}
$temp = $value;
}
//Tested with:
set($path, $obj, '111');
In PHP you can access properties dynamically such as:
`
class test {
public testvar;
}
$newtest = new test();
$property = "testvar"
$newtest->{"testvar"} //or $newtest->{$property};
`
Depending on what you are doing you can you a foreach loop to get the key value pair as well.
`
foreach($newtest as $key=>$val){
}
`
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