0

私は会社の新しいインターンであり、この表記を見たとき、誰かのコードを調べていました。

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

中括弧のある部分がわかりません。それを入力する他の方法はありますか?そして、その構文の利点は何ですか?

4

2 に答える 2

5

その構文を使用すると、クラスのメソッドと変数をそれぞれの名前を知らなくても動的に呼び出すことができます (ドキュメントの変数変数名も参照してください)。

/編集:より洗練された例で回答を更新しました。これが理解しやすいことを願っています。元のコードを修正しました。これは実際に動作するはずです。


例:

<?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!'
?>
于 2012-08-27T08:39:21.420 に答える
1

変数の内容は、$calOptionからのクラス メンバーの名前として使用され$o_eventNodeます。中括弧は、変数の終わりを明確に示すためにあります$calOption[0]['value']

配列で可変変数を使用する場合のこのあいまいさの問題の説明については、 http: //php.net/language.variables.variable.phpを参照してください。

于 2012-08-27T08:40:28.613 に答える