Autoload to spl_autoload

I have been using __autoload for a while now and it works fine but since they recommend not using it any more I think I need to move forward. Currently I load __autoload every time I enter the system as follows:

function __autoload($object){
	  $source = $_SERVER['DOCUMENT_ROOT'] . '/classes/' . str_replace('_', '/', $object) . '.php';
	  require_once($source);
	}

A sample class would be named Admin_LogicIn and the filename would be LogicIn.php in the Admin subdirectory.

To instantiate it is just new Admin_LogicIn(arg1, arg2); and it works great!

Recently I wanted to use the Stripe library and they are structured differently with namespace and class with the same name all in one directory which would be a subdirectory on my system. So short of changing their files, which I obviously don’t want to do, I can’t instantiate their classes.

So first question, can I make the adjustment to

function my_autoload($object) {
     $source = $_SERVER['DOCUMENT_ROOT'] . '/classes/' . str_replace('_', '/', $object) . '.php';
     require_once($source);
}

spl_autoload_register('my_autoload');

Does that leave me in the same place I am now just using spl_autoload instead of __autoload? And if it does, can I ‘spl_autoload_register’ another function to cover the other library and how are namespaces handled in that case?

Thanks

Quick update, I went ahead and made the change to the spl_autoload_register and it seems to work exactly the same. I can see no difference which I suppose is good. So what is the advantage of spl_autoload_register and if I use a second register with a different function it appears to ignore it. I assume I am either missing the point here or doing something wrong. Any ideas to point me in the right direction? Thanks

The reason that you don’t see much of spl_autoload anymore is that composer will generate a nice optimized autoloader for you. So use composer to install stripes and have at it. One less headache to have to worry about. https://getcomposer.org/

Thanks, If it does that, what structure do I have to use for my files? Can they just stay the same or will it need to be modified to the namespace and/or the \ back slashes rather than the _ underscore and directory_subdirectory I am using now?

Never mind. Got it all working now. Thanks for the heads up, works great.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.