note 118061 added to function.spl-autoload-register
| From: | kakkau at grr dot la | Date: | Mon, 28 Sep 2015 05:11:30 +0000 |
| Subject: | note 118061 added to function.spl-autoload-register | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-203862@lists.php.net to get a copy of this message | ||
A note on registering autoloading functions with additional parameters.
./alf.home.php
<?php
/*
* class containing an autoloading function alias ALF :)
*/
class ALF {
public function haaahaaahaaa($class = "ALF", $param = "Melmac") {
echo "I am ".$class." from ".$param.".\n";
}
}
?>
./kate.melmac.php
<?php
require_once("alf.home.php");
/*
* the normal way is to get ALF
* and register an autoloading function
*/
$alf = new ALF();
spl_autoload_register(array($alf,'haaahaaahaaa'));
$alf->haaahaaahaaa(); // ALF is from Melmac :)
/*
* now lets try to autoload a class
*/
@$kate = new Kate(); // this throws a fatal error because
// Kate is NOT from Melmac :)
?>
I am ALF from Melmac.
I am Kate from Melmac.
./kate.earth.php
<?php
require_once("alf.home.php");
/*
* BUT what if we want to correct Kates origin ?
* How can one pass parameters to an autoloading function
* upon registering?
*
* spl_autoload_register is not suitable for that
* but we can try is to define a callable during registration
*/
spl_autoload_register(function($class){
call_user_func(array(new ALF(),'haaahaaahaaa'), $class, "Earth"); });
/*
* now lets try again to autoload a class
* Kate will still not be found but we corrected her origin :)
*/
@$kate = new Kate(); // Kate is from Earth :)
/*
* NOTE: that you cannot pass $this or another object created
* outside of the callable context using the
* registering way above. therefor you should swap your autoloading
* function to a seperate class as done at the beginning with ALF.
*
* NOTE: you may not able to unregister your autoloading function
* directly as an instance was created in another context
*/
?>
I am Kate from Earth.
----
Server IP: 72.52.91.14
Probable Submitter: 62.158.71.244
----
Manual Page -- http://php.net/manual/en/function.spl-autoload-register.php
Edit -- https://master.php.net/note/edit/118061
Del: integrated -- https://master.php.net/note/delete/118061/integrated
Del: useless -- https://master.php.net/note/delete/118061/useless
Del: bad code -- https://master.php.net/note/delete/118061/bad+code
Del: spam -- https://master.php.net/note/delete/118061/spam
Del: non-english -- https://master.php.net/note/delete/118061/non-english
Del: in docs -- https://master.php.net/note/delete/118061/in+docs
Del: other reasons-- https://master.php.net/note/delete/118061
Reject -- https://master.php.net/note/reject/118061
Search -- https://master.php.net/manage/user-notes.php