Multiple vars assignment in one sentence in PHP

后端 未结 1 1209
深忆病人
深忆病人 2020-12-20 04:56

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

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

I mean is allowed by the ID

相关标签:
1条回答
  • 2020-12-20 05:25

    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)
    
    0 讨论(0)
提交回复
热议问题