Search code examples
phpnamespacesfatal-errorclassnotfound

PHP namespace & use Fatal error class not found even when i already specified class with use


I'm running into trouble with namespace in PHP. For an example I have a file like this

namespace App\Models\Abstracts;
abstract class Country{}

and then another file like this

namespace App\Models;

use App\Models\Abstracts\Country;

class City extends Country{}

I always get the

Fatal error: Uncaught Error: Class ... not found in ...

Can anyone help me? thanks a lot.


Solution

  • To do that, I advise you to use the PSR (psr-4).

    First, let's create a files structure as bellow :

    enter image description here

    Now let's init the composer to configure the psr-4.

    jump to the root of the project (in this example the root directory of src), and run :

    you will be asked to fill some project information, just skip it

    composer init

    A file named composer.json will be created in the root directory, let's configure the psr-4 inside.

    {
        "name": "root/project",
        "autoload": {
            "psr-4": {
                "App\\": "src/"
            }
        }
    }
    

    Learn more about psr-4

    to hover, we are just telling the PSR to point the name App to the directory src and then the name of subfolder should be the surname in your namespace.

    Example:

    App => src directory 
    App\Models => src/Models directory
    

    And so on

    Next, you should generate the autoload by

    composer dump-autoload
    

    The final project file structure seems to be something like :

    enter image description here

    I create a file called index.php in the root directory to test my code, but first, you should require the autoload which has been generated by the configuration we just did.

    <?php  
      use App\Models\City;
      require __DIR__.'/vendor/autoload.php';
      $city = new City();
      var_dump($city);
    

    Result:

    /var/www/myfm/index.php:9:
    class App\Models\City#3 (0) {
    }
    

    I hope this helps you.