Sou*_*rav 3 php oop class object include
我想在类中加载配置文件.这是config.php的内容
<?php
$__error_reporting_level=1;
$server='localhost';
$user='root';
$password='';
$dbase='eauction';
?>
Run Code Online (Sandbox Code Playgroud)
sql.php的内容
<?php
include ('config.php');
error_reporting($__error_reporting_level);
class sql
{
function connect()
{
$connections = mysql_connect($server, $user,$password) or die ('Unabale to connect to the database');
mysql_select_db($dbase) or die ('Unable to select database!');
return;
}
function login($email, $pwd)
{
$this->connect();
$result = $this->qry("SELECT uid,nameF FROM user WHERE email='".$email."' AND password='".$pwd."'");
$row=mysql_fetch_array($result);
if (mysql_num_rows($result)>0)
return array($row[0],$row[1]);
else
return array(0,0);
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我使用执行代码
include ('core/sql.php');
$obj = new sql;
$data=$obj->login($email,$pwd);
print_r($data);
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
无法选择数据库!
忽略mysql注入问题,我只需要完美地执行代码
Eli*_*Eli 12
为什么不使用.ini文件?
config.ini文件
server=test
user=root
pass=pass
dbname=mydb
Run Code Online (Sandbox Code Playgroud)
在你的课堂上有类似的东西
class A {
public $config;
public function __construct() {
$this->config = parse_ini_file('config.ini', true);
}
public function sql() {
$connections = mysql_connect($this->config['server'], $this->config['user'],$this->config['password']) or die ('Unabale to connect to the database');
mysql_select_db($this->config['dbase']) or die ('Unable to select database!');
return;
}
}
Run Code Online (Sandbox Code Playgroud)
只是另一种方法,确保您的数据库也正确命名.
此外,如果要使用当前的config.php,则需要在使用变量的方法中包含.不能在该范围之外使用它.
function connect()
{
include ('config.php');
$connections = mysql_connect($server, $user,$password) or die ('Unabale to connect to the database');
mysql_select_db($dbase) or die ('Unable to select database!');
return;
}
Run Code Online (Sandbox Code Playgroud)
阅读PHP手册中的变量范围。
您已经在类声明之前将文件包括在全局范围内,而类方法范围无法访问该文件。如果要在类方法中使用这些变量,则需要通过$GLOBALS[]
或global
关键字全局访问它们,或者更好的是,将它们传递给使用它们的函数。
include ('config.php');
// Now all your variables are defined at global scope!!!
error_reporting($__error_reporting_level);
class sql
{
// Pass as params to the function
function connect($server, $user, $password, $dbase)
{
$connections = mysql_connect($server, $user,$password) or die ('Unabale to connect to the database');
mysql_select_db($dbase) or die ('Unable to select database!');
return;
}
// etc...
// etc...
}
Run Code Online (Sandbox Code Playgroud)
您可能还考虑将它们设置为类属性,并将其传递给构造函数:
class sql
{
public $server;
public $user;
public $password;
public $dbase;
public function __construct($server, $user, $password, $dbase) {
$this->server = $server;
$this->user = $user;
// etc...
$connections = mysql_connect($this->server, $this->user, $this->password);
}
}
Run Code Online (Sandbox Code Playgroud)