PHP use class in global namespace

前端 未结 5 1436
长情又很酷
长情又很酷 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条回答
  •  爱一瞬间的悲伤
    2021-01-21 19:10

    In Namespaced PHP, references to a class must include the namespace of that class, unless you have a use statement that includes that class or part of its namespace.

    So, if you have no use statement for it, then PDO and other global classes must be referenced with the leading backslash -- ie $obj = new \PDO();

    If you have a use statement that references that class, then you may reference it by just the classname:

    use PDO;
    ....
    $obj = new PDO();
    

    If you're referencing a lot of global classes, you'll need to use each of them individually if you want to avoid using the backslash every time.

提交回复
热议问题