Questions about PHP references

Source: Internet
Author: User
Reference returns

function &testReturn(){      static $b = 1;      $b += 2;      return $b;  }  $a = &testReturn();  $a = 8;  $c = &testReturn();$c = 12;$d = testReturn();  //echo $d;  function &cuitReturn(){    $a = 2;    return $a;}$cr = &cuitReturn();//echo $cr;$cr = 4;$cr1 = cuitReturn();echo $cr1;

The second function, changing the value of the assignment variable, $CR = 4; Why did the return value of the function not change?

Reply content:

Reference returns

function &testReturn(){      static $b = 1;      $b += 2;      return $b;  }  $a = &testReturn();  $a = 8;  $c = &testReturn();$c = 12;$d = testReturn();  //echo $d;  function &cuitReturn(){    $a = 2;    return $a;}$cr = &cuitReturn();//echo $cr;$cr = 4;$cr1 = cuitReturn();echo $cr1;

The second function, changing the value of the assignment variable, $CR = 4; Why did the return value of the function not change?

Your first function, the code is actually like this, because $b it is a static variable, so the function will not be released after execution.

...    //省略代码$c = &$b;$c = 12;    //此处$b为12$d = testReturn();    //$b+2echo $d; //当然是14而不是7

But the second function $a is a local variable, the function is finished, the memory of this variable is freed.

The first thing to be clear is whether the calling function returns a reference function name preceded by a &, and the assignment statement is preceded by A & so the title $cr1 = cuitReturn(); is actually not a reference to this point.

Back to the main said, why the return value is not changed, because cuitReturn the function $a is a local variable, and is not static, so the function is returned after the release, equivalent to a $cr = &cuitReturn(); reference to a local variable, which if placed in C + + will be a big event ... This means that the pointer is pointing to an unknown memory, but the PHP engine should be handled, so $rc the reference to it $a is invalid

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.