1

Simple question:
I've been exploring open source code and saw the following statement:

$this->{$worker}

What is the meaning of enclosing brackets around, and what is the difference between this and:

$this->worker
DonCallisto
  • 29,419
  • 9
  • 72
  • 100
JavaSa
  • 5,813
  • 16
  • 71
  • 121

3 Answers3

2

Curly braces are used for string or variable interpolation in PHP.

Something like

$worker = 'foo';
$this->{$worker} = 'bar';

that means

$this->foo = 'bar';

When is useful

class RandomName
{
    protected $foo;
    protected $bar;
    protected $foo_bar;

    $properties_array = array('foo', 'bar', 'foo_bar');
    if (in_array($property, $properties_array)) {
        $this->{$property} = //some value
    }
}
Community
  • 1
  • 1
DonCallisto
  • 29,419
  • 9
  • 72
  • 100
1

The first one actually uses the value of the variable $worker, while the latter uses the Expression / word worker to target the object property.

Tacticus
  • 561
  • 11
  • 24
0

The first example is using a variable as the attribute name. The second example is using a non-variable name for an attribute on your class.

Dragony
  • 1,712
  • 11
  • 20