PHP include file包含一个文件奇怪的问题!
我面临一个奇怪的问题,包括 php 文件。让我向您展示代码:
// constants.php
$MYSQL_HOST_PORT = 'localhost:3306';
// functions.php
include 'constants.php';
function getVar() {
echo $MYSQL_HOST_PORT;
}
// doSth.php
include 'functions.php';
echo $MYSQL_HOST_PORT; // The variable is visible and echoed normally as expected!
echo getVar(); // The variable is not echoed! its "".
有什么想法吗?
I face a strange problem including php files. Let me show you the code:
// constants.php
$MYSQL_HOST_PORT = 'localhost:3306';
// functions.php
include 'constants.php';
function getVar() {
echo $MYSQL_HOST_PORT;
}
// doSth.php
include 'functions.php';
echo $MYSQL_HOST_PORT; // The variable is visible and echoed normally as expected!
echo getVar(); // The variable is not echoed! its "".
Any ideas ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
其一,
echo getVar();
中的echo
永远不会打印任何内容,因为getVar
不返回值。其次,如果您(出于某种原因)希望 getVar() 本身正常工作,则需要添加一个 global $MYSQL_HOST_PORT; 行,以使其查找
$MYSQL_HOST_PORT
在全局范围内。For one, the
echo
inecho getVar();
won't ever print anything, becausegetVar
doesn't return a value.Secondly, if you (for some reason) want
getVar()
itself to work correctly, you need to add aglobal $MYSQL_HOST_PORT;
line, to make it look for$MYSQL_HOST_PORT
in the global scope.与其全局化
$MYSQL_HOST_PORT
变量,为什么不简单地将其设为常量呢?如果包含了
constants.php
,您就可以在任何地方引用MYSQL_HOST_PORT
常量。正如 zerocrate 的回答中所示,这个问题是一个范围界定问题。
getVar()
函数的封闭范围不包括$MYSQL_HOST_PORT
。Rather than globalising the
$MYSQL_HOST_PORT
variable, why not simply make it a constant?Provided
constants.php
is included, you can reference theMYSQL_HOST_PORT
constant anywhere.As indicated in zerocrate's answer, the issue is a scoping one. The enclosed scope of the
getVar()
function does not include$MYSQL_HOST_PORT
.我发现错误的一件事是,使用
echo getVar();
行,您没有从函数中获得返回值,因此您可以简单地编写getVar();
靠它自己。One thing that I can see wrong is that with the line
echo getVar();
you are not getting a return value from the function so you can simply writegetVar();
by itself.