When I use a certain namespace class, do I need to use require?

Asked

Viewed 32 times

2

I was giving a studied in some PHP features, so I came across something that generated me curiosity.

When using namespace I ended up having to do something similar to this:

use Model\User\Create
require 'User.php' //Arquivo onde se encontra a classe Create

My question is about require, for example, every time I use namespace I have to require the file where the classes are, or just have to do it when I’m not using autoload?

1 answer

1


... every time I use namespace I have to do the require of the file where the classes are, or I just have to do it when I’m not using autoload?

You just have to use the functions require, require_once, include and include_once for classes when you don’t have an autoload system for them. And not only for namespaces, but classes without namespace also.

I believe that autoload came up just to solve this problem. If you have many classes in the project, besides setting namespace, you would have to include one by one with require.

To have no problem with this, you can use the autoload of the Poser or the function spl_autoload_register.

Take an example:

spl_autoload_register(function($class) {

    $path  = 'src/' . str_replace("\\", "/", $class) . '.php';

    if (file_exists($path)) require_once $path;
});
  • 1

    Show, thank you very much! Yeah, that’s just what I kind of thought, because in my case it was just a class, but in big projects it would be a hand to have to do the require all the time. You were able to answer my question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.