0

So, I'm converting some old code into a namespace, and trying to get autoload working. I've managed to follow the many good answers on this site about how to account for the namespace part of an autoloaded class (How do I use PHP namespaces with autoload?) - no problem.

Here's a different wrinkle, though. How do I autoload classes within the same namespace?

My autoload function (defined in a global include) is something like this:

function app_autoload($class)
{
  $path = __DIR__.'/'.str_replace("\\", DIRECTORY_SEPARATOR, $class).'.php';
  if (file_exists($path))
  {
    require_once($path);
  }
}

spl_autoload_register('app_autoload');

If I have a class defined in the namespace app\nstest, I can autoload it just fine from most of my system:

namespace app\nstest;

class Test1
{
  function hello()
  {
    echo "Hello world";
  }
}

However, another class in the same namespace has issues:

namespace app\nstest;

class Test2
{
  function callMe()
  {
    $test1 = new Test1();
  }
}

If I explicitly include/require the Test1 file at the top of Test2, no problems, but the autoloader doesn't seem to be aware of the namespace, so it's loading "Test1.php" instead of "app/nstest/Test1.php".

I also tried checking the __NAMESPACE__ inside the autoloader, but it's empty.

thelr
  • 1,134
  • 11
  • 30
  • 1
    Can you show folder structure and how your calling and testing that it doesnt work? If you change `$test1 = new Test1();` to `return new Test1();`, then do `$test = new \app\nstest\Test2();print_r($test->callMe()->hello());` it will print `Hello World` – Lawrence Cherone Mar 25 '21 at 18:50
  • 1
    btw instead of rolling your own non standard autoloading structure, you should look into using composer and conform to psr, start as you mean to go on else your refactorings will need refactoring again at some point – Lawrence Cherone Mar 25 '21 at 18:52
  • I would love to use an existing one, but I'm working with a codebase that's over a decade old and has hundreds of classes. It isn't remotely PSR compliant. I'll work on the folder structure example for you. – thelr Mar 25 '21 at 18:54
  • 1
    np, just saying :) yeah so if its like [this](https://replit.com/@lcherone/nstest) then it should work – Lawrence Cherone Mar 25 '21 at 18:57
  • Hmm, something about my real-life situation isn't lining up with the minimal example. Trying to narrow that down... – thelr Mar 25 '21 at 19:05
  • Ok, turns out the problem isn't something in this example at all. Instead, Test2 is trying to reference a constant in Test1 with the classname in a variable: `$class='Test1';return $class::MY_CONST;` Looks like I need to add the namespace onto the constant (`$class=__NAMESPACE__.'\Test1';`). I may delete this question, since the answer is so far off the question as asked. – thelr Mar 25 '21 at 19:20

0 Answers0