我创建一个单例类以返回数据库连接。我唯一要做的就是从另一个php文件调用它的getInstance()
函数。
这是单例文件:
<?php
namespace stm_asc;
class PDO_Conn
{
public static $instance;
private static $host = '127.0.0.1';
private static $db = 'stm_asc';
private static $charset = 'utf8mb4';
private static $user = 'alekrabbe';
private static $pass = '<password>';
private static $dsn;
private static $opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
private function __construct() {
//
}
public static function getInstance() {
if (!isset(self::$instance)) {
try {
self::$dsn = "mysql:host=".self::$host.";dbname=".self::$db.";charset=".self::$charset.";";
self::$instance = new PDO(self::$dsn, self::$user, self::$pass, self::$opt);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
return self::$instance;
}
}
然后我从login.php
中调用函数getInstance()
,如下所示:
<?php
error_reporting(E_ALL);
ini_set("display_errors","On");
$pdo = \stm_asc\PDO_Conn::getInstance();
//session_start();
?>
<!DOCTYPE html>
<html>
[HTML CODE HERE]
</html>
但是当我尝试面包login.php
时,出现以下错误:
Fatal error: Uncaught Error: Class 'stm_asc\PDO_Conn' not found in /home/alekrabbe/PhpstormProjects/selectorHat/views/login.php:4 Stack trace: #0 {main} thrown in /home/alekrabbe/PhpstormProjects/selectorHat/views/login.php on line 4
我不确定为什么找不到类PDO_Conn,这是我的目录结构:
如果我在$pdo = \stm_asc\PDO_Conn::getInstance();
行中添加注释,则一切正常。
我正在使用PHP 7.2.7和Ubuntu 18.04
因此,我尝试按照此documentation使用自动加载器。但是仍然无法正常工作,下面是代码:
<?php
session_start();
spl_autoload_register(function ($name) {
echo "Want to load $name.\n";
throw new Exception("Unable to load $name.");
});
try {
$pdo = \stm_asc\PDO_Conn::getInstance();
$mapper = new \stm_asc\MySQL_DataMapper($pdo);
$stuff = $mapper->fetchUserByFname('Alexandre');
var_dump($stuff);
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
?>
<!DOCTYPE html>
<html>
[HTML CODE HERE]
</html>
这是显示在屏幕上的消息:
Want to load stm_asc\PDO_Conn. Unable to load stm_asc\PDO_Conn.
但是现在正在加载html,css和java脚本,我相信这是由于try catch块引起的。
我还尝试仅在login.php的开头添加require_once '../controller/database/PDO_Conn.php';
,所以看起来像这样:
<?php
require_once '../controller/database/PDO_Conn.php';
$pdo = \stm_asc\PDO_Conn::getInstance();
?>
<!DOCTYPE html>
<html>
[HTML CODE HERE]
</html>
但错误仍然存在:
Fatal error: Uncaught Error: Class 'stm_asc\PDO_Conn' not found in /home/alekrabbe/PhpstormProjects/selectorHat/views/login.php:22 Stack trace: #0 {main} thrown in /home/alekrabbe/PhpstormProjects/selectorHat/views/login.php on line 22
答案 0 :(得分:3)
解决方案1:在您的login.php
中加入课程。
<?php
require_once '../path/to/file.php';
在您的情况下:(来自login.php)
<?php
require_once '../controller/database/PDO_Conn.php';
解决方案2 :(推荐)
使用PHP自动加载器:see this simple autoload example I set for you in GitHub.