PHP use class in global namespace

前端 未结 5 1471
长情又很酷
长情又很酷 2021-01-21 18:18

I have a DB wrapper class that uses PDO and in the constructor I create a PDO object. The wrapper class is in our namespace and we are using an autoloader. The issue is that the

5条回答
  •  Happy的楠姐
    2021-01-21 18:59

    To access global objects like PDO and DateTime, you need to prefix them with a backslash. So you then have two options.

    First, either use the classes you wish to use in your name-spaced class file:

    setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            }
            catch (PDOException $e) {
                echo $e->getMessage();
                exit;
            }
        }
    }
    

    Or just use the backslash-prefixed declarations within your class:

    setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            catch (\PDOException $e) {
                echo $e->getMessage();
                exit;
            }
        }
    }
    

    Personally, I prefer the first approach.

提交回复
热议问题