Question

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.

Was it helpful?

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 ;)

OTHER TIPS

Order matters:

<?php
    class Base
    {
        protected function sayHello()
        {
            echo("Base hello\n");
        }
    }

    class Child extends Base
    {
        public function sayHello()
        {
            parent::sayHello();

            echo("Child hello\n");
        }
    }

    $obj = new Child();
    $obj->sayHello();    

?>

Base hello

Child hello

You need to define the class before you can use it. So the "new" should come after the class MyClass definition.

Also MyExtends needs to be defined before you can extend it... either beforehand in the same file, or via a "require" statement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top