1

I want to autoload to use namespace in my classes but i get a error in the index.php

Error: Fatal error: Class 'foo\B' not found ...

Example:

directories skeleton:

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

A.php

<?php

namespace foo;

class A {

   private $a;

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

}

B.php

<?php

namespace foo;

use foo\A;

class B extends A {

    private $b;

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

}

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

This question is almost the same as this one: PHP autoload namespace but I include the index.php in other Folder and does not work.

If I put the same project but with the next directories skeleton, I don't get any error.

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

The question is: Why if I put the index.php in a folder does not work?

Thanks

0

1 Answer 1

1

That's because the ROOT constant is pointing to /var/www/view/, not /var/www/. It changes as you move index.php to a different directory.

You might want to take a look at the function set_include_path(). With that you can set multiple root directory definitions. You can then loose the ROOT constant altogether.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.