Skip to content
Advertisement

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 AppModelsAbstracts;
abstract class Country{}

and then another file like this

namespace AppModels;

use AppModelsAbstractsCountry;

class City extends Country{}

I always get the

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

Can anyone help me? thanks a lot.

Advertisement

Answer

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 
AppModels => 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 AppModelsCity;

require __DIR__.'/vendor/autoload.php';

$city = new City();

var_dump($city);

Result:

/var/www/myfm/index.php:9:
class AppModelsCity#3 (0) {
}

I hope this helps you.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement