George
George

Reputation: 3943

PHP __set magic method

I just came across this piece of code, but I can't seem to understand what the body means:

public function __set($propName, $propValue)
{
    $this->{$propName} = $propValue;
}

what does $this->{$propName} do?

Upvotes: 0

Views: 55

Answers (2)

random_user_name
random_user_name

Reputation: 26160

The curly braces cause the variable between them to be interpolated. This can be useful in a variety of places, but in this particular place it's effectively doing this:

// if $propName = 'mike';
$this->{$propName} = 'X';
// Results in:
$this->mike = 'X';

// if $propName = 'cart';
$this->{$propName} = 'full';
// Results in:
$this->cart = 'full';

// if $propName = 'version';
$this->{$propName} = 3;
// Results in:
$this->version = 3;

Upvotes: 1

Ihor Burlachenko
Ihor Burlachenko

Reputation: 4905

$this->{$propName} accesses property named $propName. If $propName === 'name' then $this->{$propName} is the same as $this->name.

More information here: http://php.net/manual/en/language.variables.variable.php

Upvotes: 2

Related Questions