PHP:为什么函数不能使用所需文件的变量?
此代码用于从数据库返回所选$ID的名称PHP:为什么函数不能使用所需文件的变量?,php,pdo,require,Php,Pdo,Require,此代码用于从数据库返回所选$ID的名称 #DB Informations (username/password) require('/path/to/db_informations.php'); # This function return the 'name of the $ID from the db function getName($ID){ $link = new PDO($dsn, $user, $pwd); $query = "SELECT `name` FROM
#DB Informations (username/password)
require('/path/to/db_informations.php');
# This function return the 'name of the $ID from the db
function getName($ID){
$link = new PDO($dsn, $user, $pwd);
$query = "SELECT `name` FROM `tables` WHERE `id`=$ID";
$smt = $link->prepare($query);
$smt->execute();
$name = $smt->fetch(PDO::FETCH_ASSOC);
return $name['name'];
}
# db_informations contain the credentials to connect the database. ($dsn, $user, $pwd)
Mmhrequire(/path/to/db_informations.php')
在函数内部不起作用,即使我将'require();'身体的功能。我不明白我的错误,请你解释一下:
为什么PHP不包含/path/to/文件?怎么做?这是一个问题
$dsn
、$user
、$pwd
是全局变量,未在getName()
函数范围内定义
解决此问题的最快方法是使用global
function getName($ID) {
global $dsn, $user, $pwd;
// code...
}
但是,我不建议使用
全局
(它们是)。更好的做法是在全局范围内定义数据库对象(PDO),并将其传递给函数/类。这被称为。您的DB变量不在getName()函数的作用域内。您至少需要:
function getName(...) {
global $dsn, $user, $pwd;
...
}
在大图中,您不应该使用全局变量,也不应该在每个函数调用中创建DB连接。在数据库设置文件中连接数据库一次,然后在脚本的其余数据库操作中重复使用该连接。我建议您阅读有关感谢链接标记的内容!将变量解析到函数中,然后返回它们。但是,如果我必须保持数据库连接处于打开状态,我应该使用什么来代替全局变量?正如我所说,在全局范围内定义数据库对象,例如从db_信息脚本中定义。对于start,只需将其移到
getName()
函数之外即可。