PHP autoload namespace

淺唱寂寞╮ 提交于 2020-01-15 05:54:19

问题


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;
    }   

}


来源:https://stackoverflow.com/questions/19942462/php-autoload-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!