2

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.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
kunde
  • 401
  • 1
  • 6
  • 14

3 Answers3

5

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

demonking
  • 2,584
  • 5
  • 23
  • 28
  • Thank you! I really don't know why this works, but it does. If I don't extend MyClass, it works even if it's before the class declaration. Edit: I saw your response before your correction, and I assumed you wanted to change the order (without the first $obj = new MyClass();) – kunde Oct 21 '13 at 21:59
  • Yes, you are right, i have corrected my formatting , because it only one Codeblock so i have split in two . But Nice that it works – demonking Oct 22 '13 at 15:19
1

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

Josh
  • 12,448
  • 10
  • 74
  • 118
0

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.

sdanzig
  • 4,510
  • 1
  • 23
  • 27
  • I require the file where MyExtends is declared at the beginning, but still doesn't works. – kunde Oct 21 '13 at 22:00