欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > php >内容正文

php

php globals_PHP $ GLOBALS(超级全局变量),带有示例

发布时间:2023/12/1 php 56 豆豆
生活随笔 收集整理的这篇文章主要介绍了 php globals_PHP $ GLOBALS(超级全局变量),带有示例 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

php globals

PHP $全球 (PHP $GLOBALS)

PHP $GLOBALS is the only superglobal that does not begin with an underscore (_). It is an array that stores all the global scope variables.

PHP $ GLOBALS是唯一不以下划线( _ )开头的超全局变量。 它是一个存储所有全局范围变量的数组。

$GLOBALS in PHP is used to access all global variables (variables from global scope) i.e. the variable that can be accessed from any scope in a PHP script.

PHP中的$ GLOBALS用于访问所有全局变量(来自全局范围的变量),即可以从PHP脚本中的任何范围访问的变量。

Example of $GLOBALS in PHP

PHP中的$ GLOBALS的示例

We will see how to access a variable defined globally with the $GLOBALS superglobal?

我们将看到如何使用$ GLOBALS superglobal访问全局定义的变量?

PHP代码演示$ GLOBALS示例 (PHP code to demonstrate example of $GLOBALS)

<?php//global variable$name = 'my name is sam';//functionfunction sayName() {echo $GLOBALS['name'];}//calling the functionsayName(); ?>

Output

输出量

my name is sam

By defining the $name variable it automatically is stored in the superglobal variable $GLOBALS array. This explains why we can access it in the sayName() function without defining it in the function.

通过定义$ name变量,它会自动存储在超全局变量$ GLOBALS数组中。 这就解释了为什么我们可以在sayName()函数中访问它而无需在函数中定义它的原因。

PHP代码通过使用$ GLOBALS访问全局变量来查找两个数字的和 (PHP code to find sum of two numbers by accessing global variables using $GLOBALS)

<?php//global variables$num1 = 36;$num2 = 24;//function to access global variablesfunction add2Numbers() {$GLOBALS['sum'] = $GLOBALS['num1'] + $GLOBALS['num2'];}//calling functionadd2Numbers();//printing sum using global variableecho $sum; ?>

Output

输出量

60

In the code above, num1 and num2 are global variables so we are accessing them using $GLOBALS, and sum is a variable present within $GLOBALS, thus, it is accessible from outside the function also.

在上面的代码中, num1和num2是全局变量,因此我们使用$ GLOBALS访问它们,并且sum是$ GLOBALS中存在的变量,因此,也可以从函数外部对其进行访问。

翻译自: https://www.includehelp.com/php/$GLOBALS-super-global-variable-with-example.aspx

php globals

总结

以上是生活随笔为你收集整理的php globals_PHP $ GLOBALS(超级全局变量),带有示例的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。