note 112804 added to function.spl-autoload-register

From: Date: Wed, 24 Jul 2013 14:23:09 +0000
Subject: note 112804 added to function.spl-autoload-register
Groups: php.notes 
Request: Send a blank email to php-notes+get-195755@lists.php.net to get a copy of this message
I've made a little function that makes and registers a loader that seems to be safe and reliable although I'm not sure but it feels like a good idea to share, it took me some time to come up with it I hope it saves someone some time, <?php function Loader($root = "") { $loaderFunction = create_function('$class', 'include "' . $root . '$class.php";'); spl_autoload_register($loaderFunction); } ?> if you have a file system exactly like your directory tree this function works perfectly, I haven't tested it on unix, but on windows, the default loader fails when your webpage isn't in the root directory, this makes sure that it won't cause a problem if your webpage is on a subdir too just pass ../ or more drived ../../ as root and it will work like a charm, note that i couldn't use anonymous functions because then the $root variable wouldn't have the same scope as the Loader function, so the function must be created on the fly. this is a good example of this functions usage your class: root/classes/support/classic.php <?php namespace classes/support; class classic { // class def } ?> root/support/index.php <?php Loader('../'); use classes/support/classic; $cls = new classic(); //use $cls ?> the loader will make a function like this: <?php function($class) { include "../$class.php"; } //when and when the class is needed this will run the script which is indeed what we need: include '../classes/support/classic.php'; ?> hope this helps folks; ---- Server IP: 69.147.83.199 Probable Submitter: 2.177.111.45 ---- Manual Page -- http://php.net/manual/en/function.spl-autoload-register.php Edit -- https://master.php.net/note/edit/112804 Del: integrated -- https://master.php.net/note/delete/112804/integrated Del: useless -- https://master.php.net/note/delete/112804/useless Del: bad code -- https://master.php.net/note/delete/112804/bad+code Del: spam -- https://master.php.net/note/delete/112804/spam Del: non-english -- https://master.php.net/note/delete/112804/non-english Del: in docs -- https://master.php.net/note/delete/112804/in+docs Del: other reasons-- https://master.php.net/note/delete/112804 Reject -- https://master.php.net/note/reject/112804 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#195755) next »