PHP autoload namespace

2019-07-19 10:24发布

问题:

I want to autoload my classes putting only the namespace + the filename.

Example:

directories skeleton:

\var\www
  |_ foo
  |  |_ A.php
  |  |_ B.php
  |  
  |_ index.php

A.php:

<?php

namespace foo\A;

class A {

   private $a;

   public function __construct($a) {
       $this->a = $a;
   }

}

B.php:

<?php

namespace foo\B;

use foo\A;

class B extends A {

    private $b;

    public function __construct($a, $b) {
        parent::__construct($a);
        $this->b = $b;
    }   

}

index.php:

<?php

use foo\B;

define('ROOT', __DIR__ . DIRECTORY_SEPARATOR);

$b = new B('s', 2);

function __autoload($classname) {
    $namespace = substr($classname, 0, strrpos($classname, '\\'));
    $namespace = str_replace('\\', DIRECTORY_SEPARATOR, $classname);
    $classPath = ROOT . str_replace('\\', '/', $namespace) . '.php';

    if(is_readable($classPath)) {
        require_once $classPath;
    }
}

The problem is that in the class A and B I declare the namespace with the classname, and when I use it I print the variables of the __autoload and are correct, bur when call the constructor, don't find the class.

error:

Fatal error: Class 'foo\A' not found in /var/www/foo/B.php on line 7

If I only instantiate A, and I don't use B, the problem is the same.

I need to do it like this, because I want that in class B, you can't use A if you don't put the use statement, to do it more strict.

I don't now if you understand my problem for my explanation, but thanks anyway for any suggestion!!

PD: Sorry for my english skills.

回答1:

Your code should be that in classes :

A.php

<?php

namespace foo;

class A {

   private $a;

   public function __construct($a) {
       $this->a = $a;
   }

}

B.php

<?php

namespace foo;

class B extends A {

    private $b;

    public function __construct($a, $b) {
        parent::__construct($a);
        $this->b = $b;
    }   

}