Home> php教程> php手册> body text

PHP中变量生成和作用域

WBOY
Release: 2016-06-13 10:25:09
Original
793 people have browsed it

PHP中在使用一个变量之前不必事先通知PHP。第一次使用变量的地方决定了变量的作用域,有些编程语言如C语言全局变量在函数内部是可见的。而PHP中却不是这样。在PHP中创建一个函数时,必须明确用gloabl声明要用的全局变量。
如:

function printcity($cityname)
{
print("你最喜欢的城市是:$cityname");
}
$city="北京";
function citya() //定义一个函数
{
$city="广州";
printcity($city);
}
function cityb()
{
$city="深圳";
printcity($city);
}
function cityc()
{
global $city; //声名一个全局变量
printcity($city);
}
citya();//输出广州
cityb();//输出深圳
cityc();//输出北京
?>
说明:
函数内部的变量,只有在函数使用时才有效,一旦函数结束,该函数所有的变量均被清除.

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 Recommendations
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!