PHP namespaces and autoloading

208 Views Asked by At

I'm rather new to PHP or to be more specify new to projects that is at least a bit complex and has a lot of classes. Up till now using require_once was ok. However on a new project it is getting a bit messy with tons of includes of which not all are always required.

What I'm creating is a client for a complex public web service (which is not in my control). That client will then be used in applications.

I looked at spl_autoload_register but not really getting it to work. The directory of this project is:

webServiceClient/src/path/same/as/namespaces

lets say the class of the client that will be directly by applications used is in

webServiceClient/src/path/same

That class must "load" all possible required classes. How can I achieve that?

1

There are 1 best solutions below

1
On
  1. Create autoload function
  2. Register point 1 function into spl_autoload_register. link
  3. If you just have __autoload as autoload function, you have not to register it. link
  4. Write your autoload function

.

function __autoload($classname) {    
   $filename = ROOT."\\". $classname .".php"; //you can define ROOT by define('ROOT','dir path');    
   include_once($filename);    
}

So, when you declare

$myclass = new webServiceClient\src\path\same;

autolaod will include ROOT.'webServiceClient\src\path\same.php'