Ardatr
Ardatr

Reputation: 121

Cannot Extend and Implement at the Same Time

I get an error when I try to instantiate the following:

$main = new Main();
$main->run();    

class Main
{
  public function run() {
    $instance = new C();  
  }
}

Error:

Fatal error: Class 'C' not found in /path/to/file/test.php on line xx

Everything needs to be in the same file, so I have the following setup for classes and interfaces:

interface A { ... }
abstract class B { ... }
class C extends B implements A { ... }

This order makes sense and I cannot figure out why it doesn't work. Also, the Main class is defined before interface A.

Upvotes: 0

Views: 176

Answers (1)

Tala
Tala

Reputation: 927

The code order is incorrect. like most interpreters and compilers, php is a top to bottom language, meaning that everything that is used, must be defined before the usage.

The correct order for the code is as follows:

/*1*/ interface A { ... }
/*2*/ abstract class B { ... }
/*3*/ class C extends B implements A { ... }
/*4*/ class Main
      {
          public function run()
          {
              $instance = new C();  
          }
      }
/*5*/ $main = new Main();
/*6*/ $main->run();

Upvotes: 1

Related Questions