-1

There is a foreach loop that iterates attributes. If an object has the next attribute, the code assigns a value for this attribute:

foreach ($record as $attribute=>$value) {
    if ($object->has_attribute($attribute)) {
        $object->$attribute = $value;
    }
}

I don't understand why we have to use $object->$attribute instead of $object->attribute? The latter seems more logical to me because it looks like basic OOP, but in this case the script doesn't work.

I just want to know why. Please give me some insights.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
EldinPHP
  • 13
  • 1
  • 3
  • 1
    He asks for `$object->$attribute = $value;` not `$record as $attribute=>$value` I think – Karol Gasienica Nov 04 '16 at 18:21
  • Karol is right, I ask for " $object->$attribute " ... thanks guys for those links .... i am still learning – EldinPHP Nov 04 '16 at 18:22
  • Either way, the links in there explain both scenarios; most particularly this one http://stackoverflow.com/questions/3737139/reference-what-do-various-symbols-mean-in-php IMHO and should read more on OOP. http://php.net/manual/en/language.oop5.php – Funk Forty Niner Nov 04 '16 at 18:22
  • Say we declare this: `$property = 'user';`, we can then use this to call the `$user = 'Bob';` variable like so : `echo $$property;` its the same principle. ( outputs bob ) – Jaquarh Nov 04 '16 at 18:26
  • thanks for all the comments, I got my answer, much appreciated guys <3 <3 – EldinPHP Nov 04 '16 at 18:34

2 Answers2

1

It is a feature called variable variables:

Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
  • Which this Q&A http://stackoverflow.com/questions/3737139/reference-what-do-various-symbols-mean-in-php outlines *"Variable Variables"* where IMHO, the question's a dupe, given the answer. – Funk Forty Niner Nov 04 '16 at 18:37
  • @Fred-ii-, yes, with some effort I have found _What does the PHP syntax $var1->$var2 mean?_ entry in the list (not in the `$$ Variable Variables` section, by the way) – Ruslan Osmanov Nov 04 '16 at 18:43
0

Basically, it's a dynamical attribution :

$attribute = 'toto'; 
$object->$attribute = 'tata';
echo $object->toto; // will display 'tata'
Fky
  • 2,133
  • 1
  • 15
  • 23