Search code examples
phpmysqlpdophpstormintellisense

PDO class could not be found in PhpStorm


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.

The issue that I am getting

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.

PDO files included within PhpStorm

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.


Solution

  • 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.

    • Adding a leading backslash to a class name is a way to reference its absolute namespace path.
    • In this case, the PDO classes are in the root namespace, so they are just \PDO etc; if they were in a namespace called Acme\Widgets, you would write \Acme\Widgets\PDO as the fully-qualified class name.
    • Fully qualifying the name like this is necessary if the file you are writing is itself declaring code in a particular namespace; that is, if it has the 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.
    • If this is the case, it is not just PHPStorm which will not be able to find the class - PHP itself will also fail to find the class. PHPStorm is pointing out an error to you so you can fix it before you run the code.