使用 Require_once() 正确包含数据库连接变量 [英] Use Require_once() to include database connection variables correctly
问题描述
我是 php 新手(但在其他语言方面有很长时间的开发经验),我正在PHP、MySQL 和 JavaScript"中尝试一些示例数据库连接.它显示了一个包含数据库连接变量(服务器名、用户名、密码、数据库等)的示例文件.我有一个 php 文件,其中包含一些我编写的函数,其中一个包含一些 SQL 查询.无论出于何种原因,在该文件中调用 require_once 都不会输出任何错误(我有 E_ALL 配置),但我的数据库 php 文件中的那些变量为空.
I'm a php newbie (but long time developer in other languages) and I'm trying some example db connections in "PHP, MySQL, & JavaScript". It shows an example file to include db connection variables (servername, username, password, database, etc.). I have a php file which has a handful of functions I wrote and one of them has a few SQL queries. For whatever reason, calling require_once in that file doesn't output any errors (I have E_ALL config'd) yet those variables in my database php file are null.
我用该函数中的所有变量调用了一个 echo 来查看到底发生了什么,当然它会打印一个空行.世界上有什么超出范围?我必须遗漏一些简单的东西.
I called an echo with all the variables within that function to see what the heck is going on and of course it prints a blank line. What in the world is out of scope? I have to be missing something simple.
这是我正在做的一个例子
Here's an example of what I'm doing
db_login.php
<?php
$db_server = 'localhost';
// ....
?>
functions.php
<?php
require_once('db_login.php');
function myfunction() {
echo "$db_server";
// ...
}
?>
说我疯了,但这不是应该简单到可以工作吗?
Call me crazy, but shouldn't this be simple enough to work?
推荐答案
您在 db_login.php
中声明的变量是全局变量.为了在您的函数中访问它们,您需要使用 $GLOBALS
变量,例如$GLOBALS['db_server']
,或者使用 global
关键字在你的函数中将它们声明为全局的,例如全局$db_server
.
The variables you declare in db_login.php
are globals. In order to access them in your function, you need to use the $GLOBALS
variable, e.g. $GLOBALS['db_server']
, or declare them as global inside your function using the global
keyword, e.g. global $db_server
.
这篇关于使用 Require_once() 正确包含数据库连接变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!