Real example of "=&" usage

This question already has an answer here:

  • What do the “=&” and “&=” operators in PHP mean? 2 answers

  • Here's a very simple example. You are assigning the reference of $var1 to $var2 , so when you change $var2 , $var1 value changes.

    <?php
    $var1 = 10;
    $var2 = 20;
    $var2 = &$var1;
    $var2 = 200;
    echo $var1; // 200;
    

    Suppose some user defined function manipulate a string:

    function test($string){
        $string.='bar';
        return $string;
    }
    

    In this case, you would have to attribute the return of the function back to the variable:

    $foo='foo';
    $foo=test($foo);
    

    Passing the variable by reference you could eliminate some code:

    function test(&$string){
        $string.='bar';
    }
    
    $foo='foo';
    test($foo);
    

    Just like, for example, the native settype works. Look the ampersand at the manual.


    Really useful example is modifying tree-alike structures:

    Assuming you have a tree path like 'abc' and an array:

    array(
        'a' => array(
            'b' => array(
                'c' => array(),
            ),
        ),
    )
    

    and you need to insert a new value in the deepest element. That you could end up with something like (not tested, just for demonstration purposes):

    $parts = explode('.', $path);
    $node = &$tree;
    foreach ($parts as $part) {
        if (isset($node[$part])) {
            $node = &$node[$part];
        } else {
            $node = null;
            break;
        }
    }
    
    if (!is_null($node)) {
        $node[] = 'new value';
    }
    
    链接地址: http://www.djcxy.com/p/57590.html

    上一篇: &(&符号)符号在这种情况下意味着什么?

    下一篇: “=&”用法的真实例子