简体   繁体   English

如何解决此PHP类错误

[英]How to solve this PHP class error

Here is my code 这是我的代码

<?php
class db extends PDO {
    private $error; private $sql; private $bind; private $errorCallbackFunction; private $errorMsgFormat;

    public function __construct($dsn, $user="", $passwd="") {
        $options = array(
            PDO::ATTR_PERSISTENT => true, 
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );

        try {
            parent::__construct($dsn, $user, $passwd, $options);
        } catch (PDOException $e) {
            $this->error = $e->getMessage();
        }
    }

But that line $this->error = $e->getMessage(); 但是那行$this->error = $e->getMessage(); is showing error like this 显示这样的错误

Warning: Creating default object from empty value in C:\\Program Files (x86)\\Ampps\\www\\blog\\library\\class-database.php on line 14 警告:从第14行的C:\\ Program Files(x86)\\ Ampps \\ www \\ blog \\ library \\ class-database.php中的空值创建默认对象

I have created the code like this 我已经创建了这样的代码

$db = new db("mysql:host=localhost;port=3306;dbname=".$dbname, $dbusername, $dbpassword);

and for testing other value were correct except $dbname as i want to show user that they inserted incorrect database details. 和测试其他值是正确的,除了$ dbname,因为我想向用户显示他们插入了不正确的数据库详细信息。

I'm trying to find documentation for this, but basically it seems that after the exception is thrown in the reference to $this is set to null. 我正在尝试为此找到文档,但是基本上看来,在将对$ this的引用中引发异常之后,它设置为null。 For example if you print_r($this) just before $this->error you'll get nothing. 例如,如果在$ this-> error之前打印print_r($ this),您将一无所获。

The best I can come up with in the way of an explanation for this is the source code for the PDO extension which seems to set the object to null if there's an error. 对于这种情况,我能提供的最好的方法是PDO扩展源代码,它似乎在出现错误时将对象设置为null

Regardless of that – it's bad practice to conceal (catch) an exception in a constructor which could lead to an invalid state. 无论如何–在构造函数中隐藏(捕获)异常可能会导致无效状态,这是一种不好的做法。 I'd recommend simply removing the try catch from within the constructor and put it wherever you instantiate the object (which should probably only be once in your application). 我建议只从构造函数中删除try catch,并将其放在实例化对象的任何位置(在您的应用程序中应该只能出现一次)。 Then you can deal with that exception appropriately (most likely exit the application). 然后,您可以适当地处理该异常(很可能退出应用程序)。

Alternatively, you could encapsulate the PDO class rather than extending it. 另外,您可以封装PDO类而不是对其进行扩展。

Also, this particular code snipped doesn't inspire a great deal of confidence in the wrapper you're using. 此外,这段特定的代码片段并不会激发您对使用的包装程序的信心。 You may like to take a look at a fully fledged ORM like doctrine or propel . 您可能想看一看成熟的ORM,例如学说推进

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM