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?

3
  • 1
    Have you tried or are you asking one of us to try? Commented Nov 23, 2012 at 9:35
  • @eisberg I tried. Didn't get any return value. Commented Nov 23, 2012 at 9:51
  • @Jonas Ballestad This sounds like your error reporting is off or low. Commented Nov 23, 2012 at 9:52

4 Answers 4

13
$query = $this->Queryparts->{$type}['filter'];
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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.
@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.
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});

Comments

0

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

$a = array('car', 'plane');
$varname = 'a';
var_dump($$varname);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.