Front-end PHP entry -013-variable scope

Source: Internet
Author: User

At the moment, we know a few different rules:

    • When a function is defined, the variable that is enclosed in parentheses is a formal parameter (formal parameter), which has no relation to a variable outside the body of the function. It's just inside the function.
    • Variables declared within a function are also irrelevant to variables outside the function.

However, we will encounter such a situation in the actual processing situation:

    • I want to define variables in the function body for external use
    • I want to get the variables outside the function body to use in the body.
1. Read external variables via $globlas
  
  1. <?php
  2. $one = 10;
  3. function demo(){
  4. $two = 100;
  5. $result = $two + $GLOBALS[‘one‘];
  6. return $result;
  7. }
  8. //你会发现结果变成了110
  9. echo demo();
  10. ?>

in the example above : we get the function body to use the variable outside the function body through $globals. Therefore, a variable outside the function cannot be used within the function body.

2. Modify the external variables within the function by $globlas
  
  1. <?php
  2. $pangsir = ‘我是一个兵,来自老百姓‘;
  3. function test(){
  4. echo ‘执行了函数test哟<br />‘;
  5. //调用test()函数,将通过$GLOBALS[‘pangsir‘],把$pangsir 的值改变掉
  6. $GLOBALS[‘pangsir‘] = ‘帮助别人很快乐‘;
  7. }
  8. test();
  9. //发现是不是输出的值变了呀?
  10. echo $pangsir;
  11. ?>

By the example above: we found that through GLOBALS [ PaNg sI R- ],put G l O B A L S [ p a n G s i r ] , put The value of the Pangsir is changed, so the value changes when the last output $pangsir.

3. Create a global variable within a function by $globlas
  
  1. <?php
  2. function hello(){
  3. $GLOBALS[‘que‘] = ‘提神喝茶更好哟‘;
  4. echo ‘你调了一下函数hello<br />‘;
  5. }
  6. hello();
  7. echo $que;
  8. ?>


From for notes (Wiz)

Front-end PHP entry -013-variable scope

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.