Smarty (and other tpl ngins): assign and assign_by_ref

后端 未结 3 1812
心在旅途
心在旅途 2021-01-14 16:41

This is not just about Smarty, but I guess most template engines that have variables assigned. It\'s more a theoretical question, than a practical. I have no use case.

3条回答
  •  孤街浪徒
    2021-01-14 17:27

    As mentioned in other answers, PHP employs copy-on-write. However I do wish to answer this part of your post:

    Objects are always, automatically assigned by reference.

    This is not entirely true. They are assigned an identifier which points to an object.

    $a = new stdClass();
    $b = $a; // $a and $b now share same identifier
    $b = 0; // $b no longer contains identifier
    var_dump($a); // outputs object
    

    Contrast this with assigning by reference:

    $a = new stdClass();
    $b =& $a; // $a and $b now share same reference
    $b = 0; //
    var_dump($a); // outputs int(0)
    

    Update

    In your edit you ask:

    $a = new BigObject;
    $b = $a; // pointer, right?
    $b->updateSomethingInternally(); // $b is now changed > what about $a?
    

    Did this trigger the copy-on-write? Or are $a and $b still identical (like in ===)?

    Because $b now contains an identifier, i.e. now "points" to same object as $a, $a is also affected. There was never any copying of objects involved.

提交回复
热议问题