Why doesn't the code with the namespace?

when you try var_dump this code
namespace Model;

class Db {

 protected static $connection;

 protected function __construct() {}
 protected function __clone() {}

 public static function Connect() {
 return self::$connection = new PDO('mysql:host=localhost;dbname=trvlblog', 'root', ");
}

}

$a = Db::Connect();
var_dump($a);


You receive the error:
Fatal error: Uncaught Error: Class 'Model\PDO' not found in C:\PHP\OSPanel\domains\trvlblog\Model\Db.php:13 Stack trace: #0 C:\PHP\OSPanel\domains\trvlblog\Model\Db.php(18): Model\Db::Connect() #1 {main} thrown in C:\PHP\OSPanel\domains\trvlblog\Model\Db.php on line 13

When you remove the namespace, everything works
April 4th 20 at 00:34
3 answers
April 4th 20 at 00:36
Solution
because the namespace is declared there is no such class.
you should either specify the full namespace (in this case root), or imported via use.

https://www.php.net/manual/ru/language.namespaces....
April 4th 20 at 00:38
Solution
\PDO
April 4th 20 at 00:40
Solution
Good evening.
Put a backslash before PDO
return self::$connection = new \PDO('mysql:host=localhost;dbname=trvlblog', 'root', ");
Thank you - kamren commented on April 4th 20 at 00:43
@kamren, please. - Florencio60 commented on April 4th 20 at 00:46
@kamren, I should add that slash means global namespace. - Reba_Streich commented on April 4th 20 at 00:49
@Reba_Streich, this is the official documentation. - Florencio60 commented on April 4th 20 at 00:52

Find more questions by tags PHP