量分为全局变量和局部变量。学过c语言的童鞋都知道,全局变量的作用域是整个整个文件。在即使在函数内部也有效,但在php中,如果在函数中使用全局变量,php会认为这个变量没有定义。如果我们需要在函数内部使用这个全局变量,这时我们就需要在函数内部,这个全局变量前加关键字global。下面是自己写的一个小demo。用来证明我上面说的
<?php
$str = "string";
function test()
{
if (isset($str))
{
echo "the string is defined";
}
else
{
echo "the string is undefined";
}
}
test();
?>这是在浏览器中的运行结果:

<?php
$str = "string";
function test()
{
global $str;//上面的test函数中没有这句话
if (isset($str))
{
echo "the string is defined";
}
else
{
echo "the string is undefined";
}
}
test();
?>这是在浏览器中的运行结果:

立即学习“PHP免费学习笔记(深入)”;
以上就是php 中global关键字的使用 的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号