即使在php.ini中已安装并启用PDO,也未发现错误

时间:2019-12-22 23:39:49

标签: php pdo namespaces

我的数据库类很小,我正尝试使用using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Runtime.InteropServices; namespace Discord_Nitro_Stealer { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Point lastClick; //Holds where the Form was clicked private void Form1_MouseDown(object sender, MouseEventArgs e) { lastClick = new Point(e.X, e.Y); //We'll need this for when the Form starts to move } private void Form1_MouseMove(object sender, MouseEventArgs e) { //Point newLocation = new Point(e.X - lastE.X, e.Y - lastE.Y); if (e.Button == MouseButtons.Left) //Only when mouse is clicked { //Move the Form the same difference the mouse cursor moved; this.Left += e.X - lastClick.X; this.Top += e.Y - lastClick.Y; } } private void Form1_Load(object sender, EventArgs e) { editor.Language = FastColoredTextBoxNS.Language.Custom; } private void Panel2_Paint(object sender, PaintEventArgs e) { } private void Panel1_Paint(object sender, PaintEventArgs e) { } } } 连接到我的数据库,但出现此错误:

  

致命错误:未捕获的错误:在/var/www/html/app/lib/DB.php:11中找不到类'app \ lib \ PDO'

我检查是否使用以下代码启用了PDO

PDO

输出为“是”。

我还检查了我的if ( extension_loaded('pdo_mysql') ) { exit('yes'); } ,但确实有这一行(无半列):

php.ini

这是我的extension=pdo_mysql 代码:

DB.php

这是我的自动加载器(namespace app\lib; class DB{ private static $instance = null; public $pdo; private function __construct(){ try { $this->pdo = new PDO('mysql:host=127.0.0.1;dbname=db', 'user', 'password'); } catch (PDOException $e) { exit($e->getMessage()); } } public static function instance(){ if(!isset(self::$instance)){ self::$instance = new self(); } return self::$instance; } } )文件:

init.php

这是我尝试设置新的define('DS', DIRECTORY_SEPARATOR); spl_autoload_register(function($namespace){ $path = dirname(__FILE__) . DS . str_replace('\\', DS, $namespace . '.php'); if(file_exists($path)){ require_once $path; } }); 连接的方法:

DB

P.S:如果我不使用名称空间并使用程序代码,则Pdo可以工作:

require_once 'init.php';

$db = app\lib\DB::instance(); 

1 个答案:

答案 0 :(得分:1)

  

如果我不使用名称空间,Pdo会起作用

这是解决方案的关键。 PDO是PHP中的类。所有类名都应完全限定,否则PHP将仅在当前名称空间中查找该类的定义。要在除全局名称空间之外的任何其他名称空间中使用PDO,您需要借助单个\

来指定全局名称空间。
$this->pdo = new \PDO('mysql:host=127.0.0.1;dbname=db', 'user', 'password');

旁注。建议不要使用创建PDO实例的方式。您应该指定字符集并启用PDO错误报告。

$this->pdo = new \PDO('mysql:host=127.0.0.1;dbname=db;charset=utf8mb4', 'user', 'password', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false,
]);

从不捕获异常,仅捕获die/exit 。让异常冒出来,或者正确处理它们。手动向用户显示错误消息是潜在的安全问题。