php 定义的变量有空值
我在 config.inc.php 中存储了一些数据库信息,我试图使用它来访问我拥有的类中的数据库,但由于某种原因,变量为空。 这是代码:
<?php
require_once 'dbinterface.php';
require_once 'config.inc.php';
class user {
...
function user($id) {
$this->db = new db($DB['host'], $DB['user'], $DB['pass'], $DB['database']);
...
}
...
?>
这是 config.inc.php:
<?php
$DB['host'] = '192.168.1.107';
$DB['user'] = '****';
$DB['pass'] = '****';
$DB['database'] = 'qa';
?>
我不确定为什么我得到空值,但这是我的证明:
致命错误:未捕获的异常 “异常”,消息“无数据库” 选择'于 D:\开发\PHP\qanda\dbinterface.php:18 堆栈跟踪:#0 D:\development\PHP\qanda\user.class.php(17): db->db(NULL, NULL, NULL, NULL) #1 D:\development\PHP\qanda\log.php(17): user->user('1') #2 {main} 抛出 D:\development\PHP\qanda\dbinterface.php 第 18 行
I have some database information stored in config.inc.php and i'm trying to use it to access the database in a class I have, but for some reason, the variables are null. heres the code:
<?php
require_once 'dbinterface.php';
require_once 'config.inc.php';
class user {
...
function user($id) {
$this->db = new db($DB['host'], $DB['user'], $DB['pass'], $DB['database']);
...
}
...
?>
and here's config.inc.php:
<?php
$DB['host'] = '192.168.1.107';
$DB['user'] = '****';
$DB['pass'] = '****';
$DB['database'] = 'qa';
?>
I'm not sure why i'm getting nulls, but here's my proof:
Fatal error: Uncaught exception
'Exception' with message 'No database
selected' in
D:\development\PHP\qanda\dbinterface.php:18
Stack trace: #0
D:\development\PHP\qanda\user.class.php(17):
db->db(NULL, NULL, NULL, NULL) #1
D:\development\PHP\qanda\log.php(17):
user->user('1') #2 {main} thrown in
D:\development\PHP\qanda\dbinterface.php
on line 18
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您必须将
$DB
声明为global
才能使其工作:并且在您的类定义中:
You would have to declare
$DB
asglobal
for this to work:And in your class definition:
您遇到变量作用域问题。 如果您的 config.inc 文件包含在全局上下文中,那么这应该可以工作:
You have a variable scoping issue. If your config.inc file is included in the global context, then this should work:
您将文件包含在类的范围之外。 如果将需求移至函数内部,它将按预期工作。
更好的选择是将其包含在构造函数中,循环遍历
$DB
数组,并将其值分配给$this->DB
,以便您可以访问它在班级的任何职能中。 您还需要修改函数以使用$this->DB
而不是$DB
。You're including the files outside of the class's scope. If you move the requires to inside the function, it will work as expected.
A better option would be to include it inside a constructor, loop through the
$DB
array, and assign its values to$this->DB
, so you can access it in any function of your class. You'll also need to modify your functions to use$this->DB
instead of$DB
.一般来说,使用全局变量是一个坏主意。 在这种情况下,它可以工作,但不是最佳的。 最好的想法是使用定义。
Generally, using global variables is a bad idea. In this, case it works but it isn't optimal. The best idea is to use definitions.
查看 有关变量作用域的 PHP 帮助页面,特别是“全局”关键字。 它应该可以满足您的需求。 祝你好运!
Check out the PHP help page on variable scope and in particular the "globals" keyword. It should get you what you need. Good luck!