Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curly Braces Notation in PHP

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.

like image 841
Tarik Avatar asked Jan 29 '12 19:01

Tarik


People also ask

What is curly braces PHP?

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"

What is curly brace notation?

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..

What is ${} in PHP?

${ } (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.

What do brackets mean in PHP?

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.


1 Answers

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'].

like image 199
mrlee Avatar answered Oct 22 '22 04:10

mrlee