Omar Tariq
Omar Tariq

Reputation: 7724

PHP Composer PSR-4 Autoloading And Sub-Namespaces, Class Not Found

This question is independent but I did ask a similar question before:-

Composer Gives Error, "Class Not Found"

The problem was solved but I failed to explain the nesting issue. I thought it will be more appropriate to make a new question.

I searched a lot but I can't make the nesting namespaces to work with psr-4 autoloading.

Directory Structure:-

│   composer.json
│   run.php
│
├───src
│   ├───one
│   │       parentclass.php
│   │
│   └───two
│           childclass.php
│
└───vendor
    │   autoload.php
    │
    └───composer
            autoload_classmap.php
            autoload_namespaces.php
            autoload_psr4.php
            autoload_real.php
            ClassLoader.php
            installed.json
            LICENSE

parentclass.php:-

<?php

namespace myns\one;

abstract class parentclass
{
    abstract public function abc();
}

childclass.php:-

namespace myns\two;

namespace myns\one;

use myns\one\parentclass as parentclass;

class childclass extends parentclass
{
    public function abc()
    {
        echo 'hello world';
    }
}

composer.json:-

{
    "name": "myvendor/mypackage",
    "description": "nothing",
    "authors": [
        {
            "name": "Omar Tariq",
            "email": "[email protected]"
        }
    ],
    "require": {},
    "autoload": {
        "psr-4": {
            "myns\\": "src/",
            "myns\\one\\": "src/one/",
            "myns\\two\\": "src/two/"
        }
    }
}

run.php:-

<?php

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

use myns\two\childclass as childclass;

$childclass = new childclass();
$childclass->abc();

When I run php run.php. It gives error:-

Fatal error: Class 'myns\two\childclass' not found in C:\wamp\...\run.php on line 7

Upvotes: 2

Views: 7304

Answers (2)

HPierce
HPierce

Reputation: 7409

A class can only declare one namespace in the file. By including two namespaces in childclass.php, you are likely overriding the first.

A full example can be seen here of using multiple namespaces, but the file only includes 1 namespace declaration. That said, I suspect for your case you simply made a mistake and only need one namespace.

Because the file is located in myns\two; you should use namespace myns\two; and remove the other.

Upvotes: 2

You should only add

"autoload": {
    "psr-4": {
        "myns\\": "src/"
    }
}

The other two you added may be conflicting the namespace, because you are overriding it and tell to point to the same root /src

Upvotes: 1

Related Questions