Sebastian Rush
Sebastian Rush

Reputation: 538

PHP access object values dynamically by variable name

I have this little snippet:

$action = $_GET['action'];
// some other code

// works
$properties = $client->__soapCall($action, array(
    array(
        'Page' => $x
    )
));

// try to get access to values by var $action
$obj = $properties->$action->item;

This gives me an error. My intention was to use the script only once for multiple operations by getting different actions.

...but I have no idea how to solve this and I haven't found any helpful posts or articles.

var_dump($properties):

object(stdClass)#84 (4) {
    ["PropertyGroups"]=>
        object(stdClass)#85 (1) {
            ["item"]=>
                array(73) {
                    [0]=>
                        object(stdClass)#86 (7) {
                            ["PropertyGroupID"]=>int(1)
                        }
                }
          }
  }

Upvotes: 0

Views: 100

Answers (1)

Alexander Mikhalchenko
Alexander Mikhalchenko

Reputation: 4565

The script and this line

$obj = $properties->$action->item;

Are absolutely OK. But, as you pointed out in the comments,

If action = GetPropertyGroups, Undefined property: stdClass::$GetPropertyGroups

You have PropertyGroups property in $properties, not GetPropertyGroups.

You should check if the property you're looking for exists:

property_exists($properties, $action)

Upvotes: 1

Related Questions