WoodyTheHero
WoodyTheHero

Reputation: 241

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

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 function __construct() {
    $db = new PDO(params);
  }
}

This gives me:

PHP Fatal error: Class 'Woody\PDO' not found in /var/www/test.php

Upvotes: 24

Views: 10113

Answers (3)

hakre
hakre

Reputation: 197832

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.

Upvotes: 38

ain
ain

Reputation: 22759

Add a backslash before class name, ie

$db = new \PDO(params);

Upvotes: 6

Steve Hill
Steve Hill

Reputation: 2321

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.

Upvotes: 3

Related Questions