note 85161 deleted from function.spl-autoload-register by danbrown
| From: | danbrown@php.net | Date: | Thu, 24 Mar 2011 14:46:40 +0000 |
| Subject: | note 85161 deleted from function.spl-autoload-register by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-178162@lists.php.net to get a copy of this message | ||
Note Submitter: emailmatthijs at gmail dot com
----
This is my version of making it possible to throw exceptions within autoload functions. I liked the
functions which used __construct and __callStatic to throw the exceptions, but I did not want to
relay on __callStatic because it only exists since PHP version 5.3.0. I tested all three examples
below in PHP version 5.2.6. The class named Test and Test_Interface did both not exists.
<?php
new Test();
Test::test();
class Test implements Test_Interface {}
?>
In all three cases it succesfully throwed the exception without any fatal errors.
<?php
function __autoload($sClass)
{
try
{
throw new Exception('It works');
}
catch (Exception $oException)
{
throwAutoloadException($sClass, $oException);
}
}
function throwAutoloadException($sClass, Exception $oException)
{
// The use of eval is risky, because it could be easily exploited. To prefend
// that the use of eval in this method could be exploited we make sure that the
// variable contains only the allowed characters of a class name.
if (preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $sClass))
{
eval('class '.$sClass.'
{
static public function throwException()
{
throw unserialize(\''.serialize($oException).'\');
}
}
'.$sClass.'::throwException();');
}
}
?>