Reputation:
So, here is some code that I have in my project. Recently started to use PDO methods for connecting to database etc. The problem is that the IDE that I am using (PhpStorm) can't for some reason find any PDO
classes. PhpStorm just shows a yellow line underneath the word and says 'Undefined class PDO'.
The weird thing is that if I put a \
before the word PDO
, (ie. \PDO
) then the class can now be found. I know that from doing some research that you can include it like so use \PDO
, however I don't really want to have to do that.
Lastly, wanted to mention that in external libs within PhpStorm that PDO is included which is even more confusing but hopefully you guys would be able to help me out with this.
EDIT - Answer
Ok, after some help I was able to find out why I was getting this issue. At the top of this file I had namespace App\DB;
because of this Php was not able to find the PDO
class. So, actually putting a \
in front is actually the correct way to do it.
Big thanks to IMSoP, tete0148, Jim Wright.
Upvotes: 0
Views: 2083
Reputation: 97718
I think you have jumped to the conclusion that PHPStorm is telling you the wrong thing, but actually you need to learn how namespaces in PHP work.
\PDO
etc; if they were in a namespace called Acme\Widgets
, you would write \Acme\Widgets\PDO
as the fully-qualified class name.namespace
keyword at the top of the file. In that case, the bare name PDO
is assumed to be a class in the same namespace you are writing code in. If your file begins namespace ZOulhadj\DB
, then new PDO
will be expanded as though you'd written new ZOulhadj\DB\PDO
.Upvotes: 1
Reputation: 6058
@yann-chabot's (deleted) answer is correct that it will work if you add \
before the classes but he is not clear on why.
In PHP backslashes are used to determine namespaces, and the PDO class is in the root namespace.
If you are in the same namespace as another class, you do not need to specify the namespace when using it. Otherwise, you should specify the namespace.
A simple way of thinking about namespaces are as folders.
For more info see the PHP manual.
Upvotes: 1
Reputation: 2384
Just add a backslash before class names because PHP standard classes are located in the root namespace.
\PDO
\PDOException
Or add a use statement at the top of your file.
use \PDO;
use \PDOException;
Note that PHPStorm can automatically import classes by pressing alt+enter while the cursor is over a warning.
Upvotes: 4