PHP references are only allowed to be defined in function arguments, and real-time pass-through references are forbidden

Source: Internet
Author: User
14. 引用只允许定义在函数参数中,实时传递引用是禁止的。例如:// 引用定义在函数参数-允许的function defineRefInMethod(&$a){    $a = 'a';} defineRefInMethod($b);echo $b; // 'a'// 实时传递引用-禁止的function callTimePassRef($a){    $a = 'a';}callTimePassRef(&$c);echo $c; // 'a'

What are the scenarios for each of the above two cases?

Reply content:

14. 引用只允许定义在函数参数中,实时传递引用是禁止的。例如:// 引用定义在函数参数-允许的function defineRefInMethod(&$a){    $a = 'a';} defineRefInMethod($b);echo $b; // 'a'// 实时传递引用-禁止的function callTimePassRef($a){    $a = 'a';}callTimePassRef(&$c);echo $c; // 'a'

What are the scenarios for each of the above two cases?

Sometimes we handle arrays like this.

$arr = [...];foreach($arr as &$value){    // do something here...}print_r($arr);

1, the former is the transmission address, the latter is the value. The former changes to & modified variables in the function body produce global changes, while the latter does not. A function can have only one return value, typically using the return value when making changes to a single variable, and only using & when making changes to multiple variables.
2. References are allowed only in function parameters. This sentence is doubtful, it is not known where the source is, and the second half of the sentence is an incredible explanation.

In fact, the second usage will be an error.

If you do not make an error, it is also a very wonderful way of writing, because the address is read-only non-writable.

  • 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.