How to access PHP internal classes from within a custom namespace

974

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);
    }
}
463

Answer

Solution:

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);
    }
}
600

Answer

Solution:

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.

People are also looking for solutions to the problem: android - Google API Client Library giving PHP error

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.