Most of the time, we may face a situation in which the method, variable, or classes names are stored in other variables. Take a look at the following example:
$objects['class']->name;
In the preceding code, first, $objects['class'] will be interpreted, and after this, the property name will be interpreted. As shown in the preceding example, variables are normally evaluated from left to right.
Now, consider the following scenario:
$first = ['name' => 'second']; $second = 'Howdy'; echo $$first['name'];
In PHP 5.x, this code would be executed, and the output would be Howdy. However, this is not inconsistent with the left-to-right expression evaluation. This is because $$first should be evaluated first and then the index name, but in the preceding case, it is evaluated as ${$first['name']}. It is clear that the variable syntax is not consistent and may create confusion. To avoid this inconsistency, PHP 7 introduced a new syntax called uniform variable syntax. Without using this syntax, the preceding example will bring it into notice, and the desired results won't be produced. To make it work in PHP 7, the curly brackets should be added, as follows:
echo ${$first['name']};Now, let's have another example, as follows:
class Packt
{
public $title = 'PHP 7';
public $publisher = 'Packt Publisher';
public function getTitle() : string
{
return $this->title;
}
public function getPublisher() : string
{
return $this->publisher;
}
}
$mthods = ['title' => 'getTitle', 'publisher' => 'getPublisher'];
$object = new Packt();
echo 'Book '.$object->$methods['title']().' is published by '.$object->$methods['publisher']();If the preceding code is executed in PHP 5.x, it will work fine and output our desired result. However, if we execute this code in PHP 7, it will give a fatal error. The error will be at the last line of the code, which is highlighted. PHP 7 will first try to evaluate $object->$method. After this, it will try to evaluate ['title']; and so on; this is not correct.
To make it work in PHP 7, the curly brackets should be added, as in the following code:
echo 'Book '.$object->{$methods['title']}().' is published by '.$object->{$methods['publisher']}();
After making the changes mentioned before, we will get our desired output.