I was reading source of OpenCart and I ran into such expression below. Could someone explain it to me:
$quote = $this->{'model_shipping_' . $result['code']}->getQuote($shipping_address);
In the statement, there is a weird code part that is$this->{'model_shipping_' . $result['code']}
which has {}
and I wonder what that is? It looks an object to me but I am not really sure.
Introduction. PHP allows both square brackets and curly braces to be used interchangeably for accessing array elements and string offsets. For example: $array = [1, 2]; echo $array[1]; // prints 2 echo $array{1}; // also prints 2 $string = "foo"; echo $string[0]; // prints "f" echo $string{0}; // also prints "f"
The symbols "{" and "} are called braces, curly braces or curly brackets. Braces are used as bare delimiters when there are nested parentheses, in much the same way as square brackets. Braces are used in the list notation for sets. They are also used in setbuilder notation..
${ } (dollar sign curly bracket) is known as Simple syntax. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.
In PHP, elements can be added to the end of an array by attaching square brackets ([]) at the end of the array's name, followed by typing the assignment operator (=), and then finally by typing the element to be added to the array. Ordered Arrays.
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']
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With