Home > Backend Development > PHP Tutorial > php函数关于global的疑惑

php函数关于global的疑惑

WBOY
Release: 2016-06-06 20:17:53
Original
1311 people have browsed it

<code>例子1
$foo = 'bar';

   function destroy_foo() {

    global $foo;

    unset($foo);
    // $foo = '123';

}
destroy_foo();
echo $foo;  // bar
</code>
Copy after login
Copy after login

而如果把unset($foo)替换成$foo = ‘123’;

<code>//例子2
$foo = 'bar';

   function destroy_foo() {

    global $foo;

    // unset($foo);
     $foo = '123';

}
destroy_foo();
echo $foo;   // 123</code>
Copy after login
Copy after login

global引入函数体外的变量。那么函数内外$foo就是同一个变量,所以在函数体内对变量做任何更改,外面的同名函数也跟着改变,例子2就说明了这一点,但为什么例子1里,unset($foo)之后,在外面访问$foo还有值呢?

回复内容:

<code>例子1
$foo = 'bar';

   function destroy_foo() {

    global $foo;

    unset($foo);
    // $foo = '123';

}
destroy_foo();
echo $foo;  // bar
</code>
Copy after login
Copy after login

而如果把unset($foo)替换成$foo = ‘123’;

<code>//例子2
$foo = 'bar';

   function destroy_foo() {

    global $foo;

    // unset($foo);
     $foo = '123';

}
destroy_foo();
echo $foo;   // 123</code>
Copy after login
Copy after login

global引入函数体外的变量。那么函数内外$foo就是同一个变量,所以在函数体内对变量做任何更改,外面的同名函数也跟着改变,例子2就说明了这一点,但为什么例子1里,unset($foo)之后,在外面访问$foo还有值呢?

http://php.net/manual/zh/function.unset.php
里面写的很清楚。

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template