Jonathan Spiller
Jonathan Spiller

Reputation: 1895

Class instantiation above vs below class declaration

I have a class called UserController which is instantiated above its own declaration, by an ajax call to UserController.php. It works, as expected.

<?php
new UserController();

class UserController{
  //constructor
  //methods
}
?>

Now I want to provide some common functionality to all of my controllers, and have done so by extending a baseController.

<?php
//include BaseController
new UserController();

class UserController extends BaseController{
  //constructor
  //methods
}
?>

However, I get this message when the instantiation is attempted:

Fatal error: Class 'UserController' not found in C:\xampp\htdocs\project\controllers\UserController.php

If I move the instantiation to after the declaration. It all works fine again.

<?php
//include BaseController

class UserController extends BaseController{
  //constructor
  //methods
}

new UserController();
?>

Can someone please shed some light on this?

Why does instantiating the UserController class need to be done after its declaration in this case, but can be done before the declaration if not extending another class?

Upvotes: 1

Views: 666

Answers (1)

Manse
Manse

Reputation: 38147

From the docs :

Unless autoloading is used, then classes must be defined before they are used. If a class extends another, then the parent class must be declared before the child class structure. This rule applies to classes that inherit other classes and interfaces.

Reference here

and include is not autoloading ... so there is your problem

Upvotes: 1

Related Questions