3

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.

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
tieuhoanglinh
  • 53
  • 1
  • 3
  • Are the files containing those classes included? Are you using some autoloader? `use` doesn't include the actual file by itself, that needs to either be done manually, something like: `require_once '/path/to/Country.php';` or using some autoloader. The `use` is only to be able to reference the class name directly without needing to include the complete namespace every time. `extends Country` instead of `extends \App\Models\Abstracts\Contry` – M. Eriksson Jun 20 '20 at 12:14

1 Answers1

5

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.

xxx
  • 1,153
  • 1
  • 11
  • 23
Yassine CHABLI
  • 3,459
  • 2
  • 23
  • 43