函数外的变量是全局变量吗?
<?php
$foo = 1;
function meh(){
// <-- $foo can't be accessed
}
它看起来不像一个全局变量。但是,如果它位于函数之外,它是否会存在诸如全局内容之类的缺点?
<?php
$foo = 1;
function meh(){
// <-- $foo can't be accessed
}
It doesn't look like a global variable. However, does it have disadvantages like global stuff if it's outside the function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在任何函数外部定义的所有变量都在全局范围内声明。如果您想访问全局变量,您有两种选择:
使用global关键字
<前><代码>
或使用$GLOBALS
<前><代码>
阅读更多内容 http://php.net/manual/en/language .variables.scope.php
All variables defined outside any function are declared in global scope. If you want to access a global variable you have two choices:
Use the global keyword
Or use the $GLOBALS
Read more at http://php.net/manual/en/language.variables.scope.php
是。可以从任何位置访问它们,包括其他脚本。它们稍微更好,因为您必须使用
global
关键字从函数内访问它们,这样可以更清楚地了解它们来自何处以及它们的作用。全局变量的缺点也存在,
Yes. They can be accessed from any location, including other scripts. They are slightly better as you have to used the
global
keyword to access them from within a function, which gives more clarity as to where they are coming from and what they do.The disadvantages of global variables apply, but this doesn't instantly make them evil as is often perceived in some OO languages. If they produce a good solution that's efficient and easily understandable, then you're fine. There are literally millions of succesful PHP projects that use global variables declared like this. The biggest mistake you can make is not using them and making your code even more complicated when it would have been perfectly fine to use them in the first place. :D
函数外部有点像全局作用域(与类 C 语言相比),但您必须做一件事才能允许访问函数内的 var:
Outside of the function is sorta like global scope (when compared to C-like languages), but you have to do one thing to allow access to the var within a function:
在您的示例中,
$foo
在全局范围内创建为变量。 (除非您显示的脚本是来自另一个函数/方法范围内的included()
。)PHP 没有真正的全局变量。您必须使用
global $foo;
语句手动为其添加别名才能访问它们。 (此外,“任何全球性的东西都是坏的”建议就是这样,糟糕的建议。)In your example
$foo
gets created as variable in the global scope. (Unless your shown script wasincluded()
from within another functions/methods scope.)PHP doesn't have real global variables. You have to manually alias it using the
global $foo;
statement to access them. (Also the "anything global is bad" advise is just that, bad advise.)如果我正确理解你的问题,那确实应该没有问题。除非你将一个变量声明为全局变量,否则它将被限制在声明它的范围内,在这种情况下,无论上面的代码定义在哪个 php 文件中。你可以在 meh() 中声明另一个变量 $foo ,它将是独立于外部定义的 $foo 。
If I understand your question correctly, there really shouldn't be a problem. Unless you declare a variable as a global, it will been limited to the scope in which it is declared, in this case whatever php file the above code is defined in. You could declare another variable $foo in meh() and it would be independent of the $foo defined outside.