PHP uses variables to specify the method name or property name of an object. A question when using dynamic features to operate on an object?

problem description

When an Object, in

PHP declares a variable whose value is a string of method or property names in an object and then calls it through dynamic characteristics, why do so many people (examples in Laravel source code and PHP manuals) like to add curly braces?

related codes


what result do you expect? What is the error message actually seen?

in fact, there will be no problem without curly braces? Why add curly braces? what is the reason for adding curly braces?

Php
Apr.02,2021

class demo
{
    protected $other;

    public function __construct($clsss){
        $this->other = $clsss;
    }

    public function call($data){
        $this->other->{$data['call']}();//
        $this->other->$data['call']();//
    }
}

class otherClass
{
    public function foo(){
        echo 'here is '.__FUNCTION__.PHP_EOL;
    }

    public function bar(){
        echo 'here is '.__FUNCTION__.PHP_EOL;
    }
}

$other = new otherClass();
$demo = new demo($other);

$data=['type' => 'login', 'call' => 'foo'];
$demo->call($data);

A more complex place may show its usefulness. See for yourself.

Menu