PHP Interview questions

Total available count: 33
Subject - PHP Frameworks
Subsubject - PHP

What are Autoloading classes?

All developers writing object-oriented applications create one PHP source file per class definition. One of the biggest annoyances is having to write a big list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is not necessary. The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are not currently defined. By registering autoloaders, PHP is given a last chance to load class or interface before it fails with an error.


Although the autoload() function can also be used for autoloading classes and interfaces, it's preferred to use the spl_autoload_register() function. This is due to it is a more flexible alternative (enabling for ‘n’ number of autoloaders to be specified in the application, such as in third party libraries). For this we are using autoload() is discouraged and it may be deprecated in the future.


Before PHP 5.3, exceptions thrown in the autoload() function could not be caught in the catch block and that result in a fatal error. From PHP 5.3 and upwards, this is possible that if a custom exception is thrown, then the custom exception class is available. The autoload() function may be used recursively to autoload the custom exception class.

Note: Autoloading is not available if you are using PHP in CLI interactive mode.

Note: If the class name is used in call_user_func() then it can contain some dangerous characters such as ../. It is recommended not to use the user-input in such functions or at least verify the input in autoload().


Below code attempts to load the classes Slightbook_InterviewQuestions and Slightbook_MultipleChoices from the files Slightbook_InterviewQuestions.php and Slightbook_MultipleChoices.php respectively.

spl_autoload_register(function ($class_name) {
   include $class_name . '.php';

$obj = new Slightbook_InterviewQuestions();
$obj2 = new Slightbook_MultipleChoices();


Next 5 interview question(s)

What is the difference between == and === in PHP?
What is the difference between self and $this?
What is the use of ::class?
Define inheritance and how it can be implemented in PHP?
What are Objects?