Problems with PHP namespaces and built-in classes, how to fix?

前端 未结 3 1192
后悔当初
后悔当初 2020-12-01 15:59

I\'m writing a small library in PHP and i\'m having some problems with built-in classes not being read. For example:

namespace Woody;

class Test {
  public          


        
相关标签:
3条回答
  • 2020-12-01 16:33

    The below should work:

    namespace Woody;
    
    class Test {
        public function __construct() {
            $db = new \PDO(params);
        }
    }
    

    You need to prefix PDO with the backslash so PHP knows it's in the global namespace.

    0 讨论(0)
  • 2020-12-01 16:34

    This:

    namespace Woody;
    use PDO;
    

    Or:

    $db = new \PDO(params);
    

    Point in case is, that the class PDO is not a full qualified name within your Namespace, so PHP would look for Woody\PDO which is not available.

    See Name resolution rulesDocs for a detailed description how class names are resolved to a Fully qualified name.

    0 讨论(0)
  • 2020-12-01 16:37

    Add a backslash before class name, ie

    $db = new \PDO(params);
    
    0 讨论(0)
提交回复
热议问题