PHP namespaces and PDO library problem

hello ,

I am trying to include namespaces on my project and i run into a problem with PDO library.

the code is

namespace application\libs;

class mysqlDb {

	public function __construct(){
	// connect to MySQL and select database
		try{
		
			$this->dbLink = new \\PDO('mysql:host='.$this->host.';port='.$this->port.';dbname='.$this->database,$this->user, $this->password, array( PDO::ATTR_PERSISTENT => false ,PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));

		}catch (Exception $e){
			throw new \\Exception('Αδύνατη η σύνδεση με τον εξυπηρετιτή');
		}
	}

I get the following error:
PHP Fatal error: require_once() [<a href=‘function.require’>function.require</a>]: Failed opening required ‘application/libs/PDO.php’

I dont understand what causes that error. Can you please help me? Thank you in advance for any help!

I think you may need to remove the backslash before PDO.
I haven’t used namespaces, but I’m assuming PHP is excepting a class called PDO which is defined in your application\libs namespace, while PDO is a globally available (built-in) class.

Thank you Immerse for your reply , I managed to solve the problem.
I added a namespace alias for the PDO before the class declaration and it worked.

The code became

namespace application\libs;

use PDO;

class mysqlDb {

public function __construct(){
// connect to MySQL and select database
try{

$this->dbLink = new \PDO(‘mysql:host=’.$this->host.‘;port=’.$this->port.‘;dbname=’.$this->database,$this->user, $this->password, array( PDO::ATTR_PERSISTENT => false ,PDO::MYSQL_ATTR_INIT_COMMAND => ‘SET NAMES utf8’));

}catch (Exception $e){
throw new \Exception(‘Αδύνατη η σύνδεση με τον εξυπηρετιτή’);
}
}

I also noticed that after adding the alias, I could add or remove the backslash and it still worked. (this means new \PDO() and new PDO() act the same ).
I may have solved the problem but some things about namespaces remain unclear inside my head.

Mine too :wink:

Glad it works now though!