0

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?

3
  • Look it up php.net/manual/en/language.oop5.overloading.php#object.set Commented Dec 17, 2015 at 17:33
  • sorry @KA_lin, my question is not on how to use magic methods, but on what the code does, I can't seem to understand the curly brace Commented Dec 17, 2015 at 17:37
  • Ah I understand now :) Commented Dec 17, 2015 at 17:40

2 Answers 2

2

$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

Sign up to request clarification or add additional context in comments.

Comments

1

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;

1 Comment

Thanks a lot, now I understand it better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.