note 99516 added to language.variables.variable
| From: | SamYong-hellclanneratlivedotcom at osu1 dot php dot net | Date: | Sat, 21 Aug 2010 09:42:48 +0000 |
| Subject: | note 99516 added to language.variables.variable | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-171909@lists.php.net to get a copy of this message | ||
Want to access object's property or array value using variable variables but not possible?
Here's a workaround to it:
<?php
function varvar($str){
if(strpos($str,'->') !== false){
// Accessing object property
$parts = explode('->',$str);
global ${$parts[0]};
return ${$parts[0]}->$parts[1];
}elseif(strpos($str,'[') !== false && strpos($str,']') !== false){
$parts = explode('[',$str);
global ${$parts[0]};
$parts[1] = substr($parts[1],0,strlen($parts[1])-1);
return ${$parts[0]}[$parts[1]];
}else{
global ${$str};
return ${$str};
}
}
$arrayTest = array('value0', 'value1', 'test1'=>
'value2', 'test2'=> 'value3');
$objectTest = (object)$arrayTest;
$test = 'arrayTest[1]';
var_dump(varvar($test)); // string(6) "value1"
var_dump($$test); // NULL
$test2 = 'objectTest->test2';
var_dump(varvar($test2)); // string(6) "value3"
var_dump($$test2); // NULL
?>
Cheers
Sam-Mauris Yong
----
Server IP: 69.147.83.197
Probable Submitter: 218.186.8.230 (proxied: 116.88.226.181)
----
Manual Page -- http://www.php.net/manual/en/language.variables.variable.php
Edit -- https://master.php.net/note/edit/99516
Del: integrated -- https://master.php.net/note/delete/99516/integrated
Del: useless -- https://master.php.net/note/delete/99516/useless
Del: bad code -- https://master.php.net/note/delete/99516/bad+code
Del: spam -- https://master.php.net/note/delete/99516/spam
Del: non-english -- https://master.php.net/note/delete/99516/non-english
Del: in docs -- https://master.php.net/note/delete/99516/in+docs
Del: other reasons-- https://master.php.net/note/delete/99516
Reject -- https://master.php.net/note/reject/99516
Search -- https://master.php.net/manage/user-notes.php