Bird
Raised Fist0
PHPprogramming~20 mins

Common autoloading mistakes in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Autoloading Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this autoloading code?

Consider this PHP code using a simple autoloader. What will be the output when running this script?

PHP
<?php
spl_autoload_register(function ($class) {
    include $class . '.php';
});

$obj = new User();
echo $obj->getName();
?>
AOutputs the user's name if User.php exists and defines class User
BFatal error: Uncaught Error: Class 'User' not found
CWarning: include(User.php): failed to open stream: No such file or directory
DOutputs nothing and no error
Attempts:
2 left
💡 Hint

Think about what happens if the file User.php exists and defines the class User.

❓ Predict Output
intermediate
2:00remaining
What error occurs with this autoloader?

What error will this PHP code produce when trying to instantiate Product?

PHP
<?php
spl_autoload_register(function ($class) {
    include 'classes/' . strtolower($class) . '.php';
});

$product = new Product();
?>
AParse error: syntax error
BFatal error: Uncaught Error: Class 'Product' not found
CNo error, object created successfully
DWarning: include(classes/product.php): failed to open stream: No such file or directory
Attempts:
2 left
💡 Hint

Check if the file path matches the class name case sensitivity.

🔧 Debug
advanced
2:30remaining
Why does this autoloader cause a fatal error?

Given this autoloader, why does instantiating Order cause a fatal error?

PHP
<?php
spl_autoload_register(function ($class) {
    require_once __DIR__ . '/src/' . $class . '.php';
});

$order = new Order();
?>
AThe file src/Order.php does not exist or path is incorrect
Brequire_once causes multiple inclusions leading to error
CThe class Order is defined with a namespace but autoloader ignores namespaces
DThe autoloader function is not registered properly
Attempts:
2 left
💡 Hint

Think about how namespaces affect file paths in autoloading.

📝 Syntax
advanced
1:30remaining
Which option causes a syntax error in autoloader registration?

Which of these autoloader registrations will cause a syntax error?

Aspl_autoload_register(function $class { include $class . '.php'; });
Bspl_autoload_register(function($class) { include $class . '.php'; });
Cspl_autoload_register(fn($class) => include $class . '.php');
Dspl_autoload_register(function($class) { require_once $class . '.php'; });
Attempts:
2 left
💡 Hint

Check the syntax of anonymous functions in PHP.

🚀 Application
expert
3:00remaining
How many files will be included when instantiating these classes?

Given this autoloader and these class instantiations, how many files will be included?

spl_autoload_register(function ($class) {
    include_once __DIR__ . '/lib/' . str_replace('\\', '/', $class) . '.php';
});

$a = new App\Controller\Home();
$b = new App\Model\User();
$c = new App\Controller\Home();
A3 files included
B2 files included
C1 file included
DNo files included
Attempts:
2 left
💡 Hint

Consider how include_once works with repeated class instantiations.

Practice

(1/5)
1. What is a common mistake when using spl_autoload_register in PHP?
easy
A. Defining classes without namespaces
B. Using include_once inside the autoload function
C. Calling the autoload function manually after registering
D. Providing an incorrect file path for the class file

Solution

  1. Step 1: Understand autoload file path usage

    The autoload function must correctly map class names to file paths to find and load the class files.
  2. Step 2: Identify common mistakes in file paths

    If the file path is wrong or misspelled, PHP cannot load the class, causing errors.
  3. Final Answer:

    Providing an incorrect file path for the class file -> Option D
  4. Quick Check:

    Wrong file path = autoload failure [OK]
Hint: Check file paths carefully in autoload functions [OK]
Common Mistakes:
  • Misspelling directory or file names
  • Ignoring case sensitivity in file names
  • Not matching namespaces to folder structure
2. Which of the following is the correct syntax to register an autoload function in PHP?
easy
A. spl_autoload_register('myAutoloadFunction');
B. register_autoload('myAutoloadFunction');
C. autoload_register('myAutoloadFunction');
D. spl_register_autoload('myAutoloadFunction');

Solution

  1. Step 1: Recall the correct PHP autoload registration function

    PHP uses spl_autoload_register to register autoload functions.
  2. Step 2: Verify syntax correctness

    The function name must be exactly spl_autoload_register with the function name as a string parameter.
  3. Final Answer:

    spl_autoload_register('myAutoloadFunction'); -> Option A
  4. Quick Check:

    Correct function name = spl_autoload_register [OK]
Hint: Remember exact function name: spl_autoload_register [OK]
Common Mistakes:
  • Using incorrect function names
  • Missing parentheses or quotes
  • Confusing with other register functions
3. Given this autoload function:
spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.php';
});

// Assuming file 'classes/Foo.php' exists and defines class Foo
$obj = new Foo();

What will happen if the file name is actually foo.php (lowercase)?
medium
A. Fatal error: Class 'Foo' not found
B. Class Foo will load successfully
C. Warning: include failed but script continues
D. Autoload function will convert filename to lowercase automatically

Solution

  1. Step 1: Understand case sensitivity in file systems

    On case-sensitive systems (like Linux), 'Foo.php' and 'foo.php' are different files.
  2. Step 2: Analyze autoload behavior

    The autoload tries to include 'classes/Foo.php' but only 'foo.php' exists, so include fails and class is not found.
  3. Final Answer:

    Fatal error: Class 'Foo' not found -> Option A
  4. Quick Check:

    Filename case mismatch = class load failure [OK]
Hint: Match class name case exactly with file name [OK]
Common Mistakes:
  • Ignoring case sensitivity on Linux
  • Assuming autoload fixes filename case
  • Not checking file existence before include
4. Consider this autoload function:
spl_autoload_register(function ($class) {
    include_once __DIR__ . '/src/' . str_replace('\\\', '/', $class) . '.php';
});

// Trying to instantiate \App\Utils\Helper
$obj = new \App\Utils\Helper();

Why might this cause a failure to load the class?
medium
A. The autoload function is not registered properly
B. The namespace backslashes are not replaced correctly
C. Using include_once prevents loading multiple classes
D. The file path does not match the namespace folder structure

Solution

  1. Step 1: Examine the str_replace for backslash replacement

    The $class parameter contains single backslash characters for namespaces (e.g., '\App\Utils\Helper').
  2. Step 2: Identify the replacement error

    str_replace('\\', '/', $class) searches for double backslashes ('\\' is string '\\'), but single backslashes are present, so no replacement occurs. Path becomes '/src/\App\Utils\Helper.php', which fails to load.
  3. Final Answer:

    The namespace backslashes are not replaced correctly -> Option B
  4. Quick Check:

    str_replace('\\', '/') does not replace single '\' [OK]
Hint: Use str_replace('\\', '/', $class) to replace single backslashes [OK]
Common Mistakes:
  • Not replacing backslashes in namespace
  • Incorrect folder names or missing folders
  • Assuming include_once causes load failure
5. You want to autoload classes from multiple directories: src/ and lib/. Which approach correctly handles this without errors?
hard
A. Use a single autoload function that checks both directories before including
B. Manually include all class files at the start of the script
C. Register two autoload functions, one for each directory, using spl_autoload_register
D. Use require_once inside autoload to load classes from both directories

Solution

  1. Step 1: Understand multiple autoload functions

    PHP allows registering multiple autoload functions with spl_autoload_register, which are tried in order.
  2. Step 2: Compare approaches for multiple directories

    Registering two separate autoload functions for each directory is clean and avoids complex path checks.
  3. Final Answer:

    Register two autoload functions, one for each directory, using spl_autoload_register -> Option C
  4. Quick Check:

    Multiple autoloads registered = clean multi-dir loading [OK]
Hint: Register separate autoloads for each directory [OK]
Common Mistakes:
  • Trying to handle all directories in one function poorly
  • Manually including files defeats autoload purpose
  • Using require_once can cause errors if file missing
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard