24

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

hakre
  • 193,403
  • 52
  • 435
  • 836
WoodyTheHero
  • 241
  • 2
  • 3
  • This is probably the same: [How to use “root” namespace of php?](http://stackoverflow.com/questions/6593621/how-to-use-root-namespace-of-php/6593676) – hakre Aug 01 '11 at 16:35

3 Answers3

38

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • thanks for a better answer than my own. I knew the solution, but I didn't explain it nearly as well as you did! – Steve Hill Aug 02 '11 at 11:40
  • The `\PDO` method doesn't work for me in `PHP 5.5.12`, but this does: `use PDO;`. – Jo Smo Jul 05 '14 at 15:45
  • 2
    @tastro: I think as well that using `use` is good practice. Then you can see at the top of the file which classes are taken in. – hakre Jul 06 '14 at 14:52
6

Add a backslash before class name, ie

$db = new \PDO(params);
ain
  • 22,394
  • 3
  • 54
  • 74
3

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.

Steve Hill
  • 2,331
  • 20
  • 27