DS.
DS.

Reputation: 3004

How to access PHP internal classes from within a custom namespace

How can I access standard internal classes from within a namespace?

namespace foo;

class Bar{
    public function __construct(){
        $connect = new \PDO('mysql:host='.$host.';dbname='.$name, $user, $pass);
    }
}

I'm getting an error

failed to open stream PDO.php

I have autoloader code that is working for my custom classes. How can I have the autoloader ignore the internal classes?

I am referring to this link and my code is based on that:

http://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.globalclass

Edit:

So if I put something like this, it seems to work fine. But then what's the point if I can't use it inside my own class? How would I make the parameters dynamic based on class properties?

namespace foo;
$connect = new \PDO('mysql:host='.$host.';dbname='.$name, $user, $pass);
class Bar{
    public function __construct(){
        //$connect = new \PDO('mysql:host='.$host.';dbname='.$name, $user, $pass);
    }
}

Upvotes: 2

Views: 1036

Answers (2)

Czar Pino
Czar Pino

Reputation: 6314

I've been abundantly using namespaces with internal PHP classes and the first code above should work fine, and it does (I tried). Chances are your PDO extension is disabled or misconfigured.

Have you checked whether PDO is available? See if the PDO class exists.

echo class_exists('PDO') ? "PDO exists\n" : "No PDO\n";

If not, you'll either have to enable it or recompile PHP with --with-pdo-mysql.

Upvotes: 1

Machavity
Machavity

Reputation: 31614

A couple of suggestions

First would be to include the PDO files directly in your class. Distasteful, I know, but sometimes necessary.

The second option would be the preferred. Create your instance of PDO elsewhere and then pass your instance to the class. It makes for less mess later on if you do this because you'll only create the connection once, instead of several times.

namespace foo;
use PDO;
class Bar{
    /** @var \PDO */
    protected $pdo;

    public function __construct(){
        $this->pdo = new PDO('mysql:host='.$host.';dbname='.$name, $user, $pass);
    }
}

Upvotes: 1

Related Questions