Search code examples
phpextendsclassnotfound

Class not found when extended


I have a class MyClass that works fine. When I create an instance using $obj = new MyClass() works like a charm. The problem is, if I extend this class MyClass extends MyExtends, it gives me an error: class MyClass not found.

Because the devil is in the details, here are some:

1) MyClass instance is created in the same file (called MyClass.php).

$obj = new MyClass();
class MyClass extends MyExtends{
}

2) The creation of obj is called using ajax

if($_POST['myAjaxFlag']){
    $obj = new MyClass();
} 

3) The ajax call returns as success, but if I print the data returned, I get that class not found error php message.


Solution

  • This is because you declare the class "MyClass" after your initialisation

    obj = new MyClass();
    class MyClass extends MyExtends{
    
    }
    

    Corrected:

    class MyClass extends MyExtends{
    }
    obj = new MyClass();
    

    Should work then ;)