2012-08-27 16 views
0

我在一家公司一个新来的实习生,我一直在寻找通过别人的代码,当我看到这个符号:

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

我不明白用大括号的部分。有没有其他的方式来键入它?那句法的优点是什么?

+0

@BorisGuery我不这么认为,问题是关于完全不同的主题。 –

回答

5

使用该语法,您可以在不知道各自名称的情况下动态调用类的方法和变量(另请参阅文档中的variable variable names)。

/编辑:用更复杂的例子更新了答案,我希望这更容易理解。修正了原来的代码,这个应该实际上工作。


实施例:

<?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!' 
?> 
1

可变$calOption的内容将被用作从$o_eventNode类成员的名称。花括号在那里,以清楚地标记变量的末尾,因此不同之处在于不改为$calOption[0]['value']

请参阅:http://php.net/language.variables.variable.php了解在使用变量变量与数组时出现的模糊性问题。