[英]PHP Include variables into a class
look, i have a class that connects to a mysql database, but i have another file that contents the username, host, password and table names, If i don't include it and write them, it works fine, but the problem begins when I include it, it returns me "Undefined variable". 看,我有一个连接到mysql数据库的类,但是我有另一个文件,该文件包含用户名,主机,密码和表名,如果我不包括它并编写它们,它可以正常工作,但是问题开始于我包括它,它返回“未定义变量”。 Thank you, here's my class:
谢谢,这是我的课:
<?php
include '../config/conexiongeneral.php';
class DbConnector {
var $theQuery;
var $link;
public function DbConnector(){
$host = $elnombredelhost;
$db = $labasededatos;
$user = $elnombredelusuario;
$pass = $lacontasena;
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
function fetchArray($result) {
return mysql_fetch_array($result);
}
function close() {
mysql_close($this->link);
}
}
?>
Well, i forget that i call this function with: 好吧,我忘记了我通过以下方式调用此函数:
<?php
include 'dbConnector.php';
$connector = new DbConnector();
$username = trim(strtolower($_POST['username']));
$username = mysql_real_escape_string($username);
$query = "SELECT usuario FROM $latablatres WHERE usuario = '$username' LIMIT 1";
$result = $connector->query($query);
$num = mysql_num_rows($result);
echo $num;
mysql_close();
?>
The problem is that you're including the file outside of the class so it's in the wrong scope (the class doesn't know about those variables). 问题是您将文件包含在类之外,因此文件的作用域错误(类不知道这些变量)。
Try this: 尝试这个:
public function DbConnector(){
include '../config/conexiongeneral.php';
$host = $elnombredelhost;
$db = $labasededatos;
$user = $elnombredelusuario;
$pass = $lacontasena;
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
Use the global
keyword to make the variables available inside the function. 使用
global
关键字使变量在函数内部可用。 Eg: 例如:
public function DbConnector(){
global $elnombredelhost;
$host = $elnombredelhost;
// ... rest of your code
}
Alternatively, you could declare the connection parameters a constants in the included file and use the constants in the connection script: 或者,您可以在包含的文件中将连接参数声明为常量,并在连接脚本中使用这些常量:
In conexiongeneral.php 在conexiongeneral.php中
define('DB_HOST', 'your_db_host');
In your connection class 在您的连接课程中
public function DbConnector(){
$host = DB_HOST;
// ... rest of your code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.