1

I am asking what could be the consequences of this var assignment definition:

$component = $id = $class = '';

I mean is allowed by the IDE (phpStorm), the code doesn't return any warnings, fatal or anything else but .... there is any but?

What do you think?

2
  • 5
    it's fine. that is standard syntax. Dec 5, 2016 at 14:12
  • I personally don't see anything wrong with it in PHP. Just be aware that this type of assignment might work differently in other languages. In javascript, I believe, this will create three variables pointing to the same object.
    – aynber
    Dec 5, 2016 at 14:14

1 Answer 1

4

This is okay.

PHP uses a copy on write system. It means that with primitive types such as strings or ints are really created in memory on change and will probably be okay in your example.

php

$component = $id = $class = 'foobar';

var_dump($component);
var_dump($id);
var_dump($class);

output

string 'foobar' (length=6)
string 'foobar' (length=6)
string 'foobar' (length=6)

But be careful when you do this with objects, objects are passed by reference and have different behavior:

PHP

class Obj
{
    public $_name;
}

$a = $b = new Obj();
$component = $id = $class = 'foobar';

$b->_name = 'Reynier'; //try to change name of second object only
$id = 'Reynier'; // try to change $id only

var_dump($a);
var_dump($b);

var_dump($component);
var_dump($id);
var_dump($class);

output

#Both object are changed
object(Obj)[1]
  public '_name' => string 'Reynier' (length=7)
object(Obj)[1]
  public '_name' => string 'Reynier' (length=7)

#only $id was changed
string 'foobar' (length=6)
string 'Reynier' (length=6)
string 'foobar' (length=6)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.