Eclipse PDT: "<class> cannot be resolved to a type" for default php classes like DateTime, Exception etc

18,350

Solution 1

There are many possible situations here; mine was an quite old project having a broken buildpath configuration. However using the GUI I wasn't able to fix it.

Adding the following line to the .buildpath file in the project folder while eclipse was closed and afterwards restarting eclipse solves the problem:

<buildpathentry kind="con" path="org.eclipse.php.core.LANGUAGE"/>

However, additionally if the code uses namespaces, one needs to use \DateTime instead of DateTime, or alternatively, add a 'use DateTime' on top;

(Solution found after digging deeper into comments of other problems using Eclipse PDT does not propose all php functions and https://bugs.eclipse.org/bugs/show_bug.cgi?id=502184)

Solution 2

If you don't have a file called .buildpath in the root folder of your project, just create it.

The content of the file should be something like:

<?xml version="1.0" encoding="UTF-8"?>
<buildpath>
    <buildpathentry kind="src" path=""/>
    <buildpathentry kind="con" path="org.eclipse.php.core.LANGUAGE"/>
</buildpath>

That's going to assign all your folders as "source folders".

That works fine in Eclipse Oxygen.3a Release (4.7.3a)

Solution 3

Mine is a little different but it worths mentioning here for the newcomer like me.
I just import project using Import > Projects from Folder or Archive. It's just a folder no more no less.
You have to right click on your imported folder > Configure > Convert to PHP Project ...
The Error on Exception is gone.

Solution 4

I recently ran into a similar situation with a project whose code is on a network server and the server went down. When it was restored the mounts had changed so some of my external libraries could not be found. This is how I fixed it:

In my project properties->php->source paths->include path libraries tab I added the paths to the external code. Then I ran Build project on my project followed by Refresh. The warnings went away.

Solution 5

@NextThursday mentions using the global scope using '\' before the class name. This is only important if you code is already scoped inside a specific namespace.

Share:
18,350
NextThursday
Author by

NextThursday

Updated on June 15, 2022

Comments

  • NextThursday
    NextThursday almost 2 years

    After some recent Eclipse updates and workspaces changes I found some problems with validation of my PHP code in PDT. After re-adding all external libraries for my projects every external class was resolvable, but for PHP base classes like "DateTime" or "Exception" I get an error/annotation "DateTime cannot be resolved to a type". PHP Validation Version is set to 7.1, but even lower settings create the error.

    How can I fix this validation problem?