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.