Curly Braces Notation in PHP

前端 未结 3 1810
南笙
南笙 2020-12-01 11:10

I was reading source of OpenCart and I ran into such expression below. Could someone explain it to me:

$quote = $this->{\'model_shipping_\' . $result[\'co         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-01 11:32

    Curly braces are used to denote string or variable interpolation in PHP. It allows you to create 'variable functions', which can allow you to call a function without explicitly knowing what it actually is.

    Using this, you can create a property on an object almost like you would an array:

    $property_name = 'foo';
    $object->{$property_name} = 'bar';
    // same as $object->foo = 'bar';
    

    Or you can call one of a set of methods, if you have some sort of REST API class:

    $allowed_methods = ('get', 'post', 'put', 'delete');
    $method = strtolower($_SERVER['REQUEST_METHOD']); // eg, 'POST'
    
    if (in_array($method, $allowed_methods)) {
        return $this->{$method}();
        // return $this->post();
    }
    

    It's also used in strings to more easily identify interpolation, if you want to:

    $hello = 'Hello';
    $result = "{$hello} world";
    

    Of course these are simplifications. The purpose of your example code is to run one of a number of functions depending on the value of $result['code'].

提交回复
热议问题