What is the point of assigning by reference?

This question already has an answer here:

  • How does the “&” operator work in a PHP function? 4 answers

  • here's some examples:

    Making aliases for very long variables

    $config = array(
       'developers' =>  => array(
             'emails' => array()
          ),
    );
    $dev_emails = &$config['developers']['emails'];
    $dev_emails[] = 'email1@tld.com';
    $dev_emails[] = 'email2@tld.com';
    $dev_emails[] = 'email3@tld.com';
    

    Naming a single value with a different name

    $result_count = mysql_num_rows();
    $table_rows = &$number_of_results;
    

    Assigning array items early

    $post = $_POST;
    $time = time();
    $article = array(
        'article_contents' => &$post['contents'],
        'article_title' => &$post['title'],
        'article_tags' => &$post['tags'],
        'insert_time' => &$time
    );
    
    if (array_filter($article) < 3) {
       throw new Exception("Required fields are blank");
    }
    
    $post['contents'] = striptags($post['contents']);
    
    # imaginary model
    # article::insert($article);
    

    ^ This one seems to be impractical even to me, but I know this was useful to me for a number of times

    Saving memory? ( just a theory )

    There's still a lot more application that will only appear when you're coding, you'll notice where it's useful when you're already coding


    At one time, it was possible that this saved memory by avoiding copying long strings. But modern versions of PHP use copy-on-write, so this isn't as much of an issue.

    That is, copy on write means if you assign $a = $b , it doesn't actually use more memory. $a internally points to the same content in memory that $b points to. But they're not supposed to be linked as though by reference. So if you modify $b , then at that moment PHP makes $a a physical copy of the original value of $b . If you modify $a , then it gets its own memory space for its new value.

    References are still useful for side effects.

    For example, when using foreach:

    $a = array(1, 2, 3);
    
    foreach ($a as $value) {
      $value *= 2; // does not change contents of $a
    }
    
    foreach ($a as &$value) {
      $value *= 2; // changes contents of $a
    }
    

    Or when passing function arguments, and you want the function to modify the value of the argument.

    链接地址: http://www.djcxy.com/p/57596.html

    上一篇: PHP不同用法的参考符号&

    下一篇: 通过引用分配的意义何在?