php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #29648 cant throw exceptions with __autoload (to catch and handle them - workaround?)
Submitted: 2004-08-13 12:30 UTC Modified: 2004-11-04 15:14 UTC
Votes:1
Avg. Score:4.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:0 (0.0%)
From: black at scene-si dot org Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.0+ OS: debian
Private report: No CVE-ID: None
 [2004-08-13 12:30 UTC] black at scene-si dot org
Description:
------------
I've tried to create an __autoload() function which would throw an exception if it can't load the class name from a file depending on the classname i request with the php code.

I couldnt catch the exception with a try/catch clause, because it always failed (see expected/actual result below).

My workaround was to add this after the first include_once statement inside the __autoload:

if (!class_exists($classname)) {
  eval("class ".$classname." { }");
}

Afterwards instead of a try/catch clause i used a method_exist call to see if a general function was defined (one that i require to have).

Reproduce code:
---------------
<?php

function __autoload($classname) {
        if (substr($classname,0,7)=="object_") {
                @include_once("include/object.".substr($classname,7).".php");
                return;
        }
        @include_once("class.".$classname.".php");
}

try {
  $object = new object_wtf("hello");
} catch (Exception $e) { echo "__autoload failed "; var_dump($object); }


Expected result:
----------------
Output: __autoload failed NULL

Actual result:
--------------
Fatal error: Class 'object_wtf' not found in /root/monotek/mono/commands/test.php on line 15


Patches

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-08-13 12:47 UTC] black at scene-si dot org
ugh, forgot to add

if (!class_exists($classname)) {
  throw new Exception();
}

after the first include_once in the example.

Ofcourse i'm throwing the exception im trying to catch ;)
 [2004-08-13 12:49 UTC] black at scene-si dot org
And the result:

Fatal error: __autoload(object_wtf) threw an exception of type 'Exception' in /root/monotek/mono/commands/test.php on line 16

(gah)
 [2004-10-29 15:16 UTC] black at scene-si dot org
requesting feedback & new versions also dont support this
 [2004-11-04 15:14 UTC] thekid@php.net
__autoload() is not allowed to fail. If it does, this is a fatal error. This is expected behaviour => no bug.

From the manual:
"By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error."
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Aug 16 01:01:28 2024 UTC