PHP 4 - Undefined class name

1.1k views Asked by At

In PHP 4, if you use a class before it's defined you get this error:

Fatal error: Undefined class name 'foo' in...

My code is:

function do_stuff(){
  if(foo::what()) ... // this code is before the php file with the foo class is included    
}

class foo{
  function what(){
  ...
  }
}

do_stuff();

is there any workaround for this (besides telling the people who use your script to update to php5) ?

3

There are 3 answers

1
Petah On BEST ANSWER

You could instead use:

call_user_func(array('foo', 'what'));

which would cause the class/method to be checked at runtime rather than compile time.

0
Xavier Barbosa On

if php4, you can test the existence of a class with class_exists. So to be compatible with php5, you can write this type of code :

<?php
function __autoload($classname) {
    include("classes/$classname.class.php");   
}

if (!class_exists('foo')) __autoload('foo');
0
Tim On

Define your classes in a file which is require_once()d at the start of your script.