$query = $this->Queryparts->{$type}['filter'];
PHP: Dynamic Object Names [duplicate]
Question
Possible Duplicate:
Get PHP class property by string
This is my original code:
function generateQuery($type, $language, $options)
{
// Base type
$query = $this->Queryparts->print['filter'];
// Language modifiers
// Additional options
return $query;
}
The "print" is an array/hash defined as an object (with "(object)" casting). I wish to do something like this:
$query = $this->Queryparts->$type['filter'];
To use the the $type variable as the object name. Is this possible?
Solution
OTHER TIPS
You can either use an intermediary variable:
$name = 'something';
$object->$name;
Or you can use braces:
$a = array('foo' => 'bar');
$object->{$a['foo']}; //equivalent to $object->bar
(By the way, if you find yourself doing this often, there might be a design problem.)
Sure, you can, here is simple example:
$obj = new stdClass();
$obj->Test = new stdClass();
$obj->Test->testing['arr'] = 'test';
$type = 'testing';
print_r($obj);
print_r($obj->Test->{$type});
You can also use variable variable names by typing $$
:
$a = array('car', 'plane');
$varname = 'a';
var_dump($$varname);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow