phpnamespacespsr-4

PHP class not found when using name spacing


I am trying to load my class through namespacing but Im struggling to find the right configuration and I keep getting a class not found error.

Here is the psr-4 property in my composer.json

"psr-4": {
    "Namespaceone\\": [
        "src/core/Modules/Moduleone",
        "src/core/Modules/Moduletwo",
    ],
    "Volvo\\": [
        "src/programme/volvo/",
        "src/programme/volvo/volvoxc"
    ]
}

Here is the file structure of src/programme/volvo:

- init.php  //Contains new Volvo()
- Volvo.php //Class Volvo
- volvoxc/
  - Volvoxc.php //Class Volvoxc extends Volvo

The files and classes:

init.php

$volvo = new Volvo(); //This returns all the properties from Volvo()

Volvo.php

namespace Volvo;
use Volvoxc;
class Volvo {
  $volvoxc = new Volvoxc();
}

Volvoxc.php //This class can not be found

namespace Volvo;
class Volvoxc extends Volvo {}

Solution

  • The PSR-4 notation in your composer.json file is slightly wrong. There must by a single entry for every namespace to use.

    "psr-4": {
        "NamespaceOne\\ModuleOne\\": "src/core/Modules/ModuleOne/",
        "NamespaceOne\\ModuleTwo\\": "src/core/Modules/ModuleTwo/",
        "Volvo\\": "src/programme/Volvo/"
    }
    

    You define these three sources and therefore you can slightly adjust your namespaces.

    <?php
    
    // src: src/programme/Volvo/VolvoXC/Volvo.php
    
    declare(strict_types=1);
    
    namespace Volvo\VolvoXC;
    
    use Volvo\Volvo as BaseVolvo;
    
    final class Volvo extends BaseVolvo
    {
    }
    

    The Volvo namespace is defined once and everything in this namespace and its subfolders will be found automatically through PSR-4 autoloading.