7

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?

Community
  • 1
  • 1
Jonas Ballestad
  • 159
  • 1
  • 1
  • 6

4 Answers4

13

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

Corbin
  • 33,060
  • 6
  • 68
  • 78
  • Ok. I might have been a little unclear ($type = 'print') This solved my problem though: "$query = $this->Queryparts->{$type}['filter'];" I am not sure how your first example would be used in my case. – Jonas Ballestad Nov 23 '12 at 09:47
  • @JonasBallestad Ah, my bad. I misunderstood the question. I thought you were trying to use `$type['filter']` as the key. Not access `Queryparts->{$type}` and then access the key `filter` of what is returned from that. The idea of using {} stays the same though. – Corbin Nov 23 '12 at 10:11
13
$query = $this->Queryparts->{$type}['filter'];
som
  • 4,650
  • 2
  • 21
  • 36
2

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});
Piotr Olaszewski
  • 6,017
  • 5
  • 38
  • 65
0

You can also use variable variable names by typing $$ :

$a = array('car', 'plane');
$varname = 'a';
var_dump($$varname);
Vince
  • 3,274
  • 2
  • 26
  • 28