0

I am a new intern at a company and I was looking through someone's code, when I saw this notation:

if($o_eventNode->{$calOption}[0]['value'] == 1)

I don't understand the part with the curly brackets. Is there some other way to type it? And what is the advantage of that syntax?

tolgap
  • 9,629
  • 10
  • 51
  • 65

2 Answers2

5

With that syntax you are able to call methods and variables of a class dynamically without knowing their respective name (also see variable variable names in the docs).

/edit: updated the answer with a more sophisticated example, I hope this is easier to understand. Fixed the original code, this one should actually work.


Example:

<?php
    class Router {
        // respond
        //
        // just a simple method that checks wether
        // we got a method for $route and if so calls
        // it while forwarding $options to it
        public function respond ($route, $options) {
            // check if a method exists for this route
            if (method_exists($this, 'route_'.$route) {
                // call the method, without knowing which
                // route is currently requested
                print $this->{'route_'.$route}($options);
            } else {
                print '404, page not found :(';
            }
        }

        // route_index
        //
        // a demo method for the "index" route
        // expecting an array of options.
        // options['name'] is required
        public function route_index ($options) {
            return 'Welcome home, '.$options['name'].'!';
        }
    }
    // now create and call the router
    $router = new Router();
    $router->respond('foo'); 
    // -> 404, because $router->route_foo() does not exist
    $router->respond('index', array('name'=>'Klaus'));
    // -> 'Welcome home Klaus!'
?>
Marco Kerwitz
  • 5,294
  • 2
  • 18
  • 17
1

The contents of the variable $calOption will be used as the name of the class member from $o_eventNode. The curly brackets are there, to clearly mark the end of the variable, so it is distinct that not $calOption[0]['value'] is meant instead.

See: http://php.net/language.variables.variable.php for an explanation of this ambiguity problem when using variable variables with arrays.

feeela
  • 29,399
  • 7
  • 59
  • 71