PHP Generators and Namespaces


PHP Generators and Namespaces Interview with follow-up questions

1. What is a generator in PHP and how does it work?

A generator is a special type of function that can pause its execution and yield values one at a time, resuming from where it left off on the next call. Generators implement the Iterator interface without requiring an array to be built upfront, making them memory-efficient for large or infinite sequences.

function fibonacci(): Generator {
    [$a, $b] = [0, 1];
    while (true) {
        yield $a;
        [$a, $b] = [$b, $a + $b];
    }
}

foreach (fibonacci() as $i => $value) {
    if ($i >= 10) break;
    echo $value . ' '; // 0 1 1 2 3 5 8 13 21 34
}

How generators work:

  1. Calling a generator function returns a Generator object immediately — no code executes yet.
  2. Each call to ->current() / each foreach iteration resumes execution until the next yield.
  3. yield $value pauses the function and passes $value to the caller.
  4. Execution resumes from after the yield on the next iteration.

Practical use — reading a large file without loading it all:

function readLines(string $path): Generator {
    $file = fopen($path, 'r');
    while (($line = fgets($file)) !== false) {
        yield trim($line);
    }
    fclose($file);
}

foreach (readLines('/var/log/app.log') as $line) {
    processLine($line); // one line in memory at a time
}

yield from (delegation) allows a generator to delegate to another generator or iterable:

function inner(): Generator { yield 1; yield 2; }
function outer(): Generator { yield 0; yield from inner(); yield 3; }

Interview note: Generators are often compared to Fibers (PHP 8.1). Both can pause execution, but generators are pull-based (the consumer requests values); Fibers are bidirectional cooperative coroutines used for async programming.

↑ Back to top

Follow-up 1

Can you explain the yield keyword in PHP?

In PHP, the yield keyword is used inside a generator function to yield a value. When the yield keyword is encountered, the generator function pauses its execution and returns the yielded value. The generator function can then be resumed later, and it will continue execution from where it left off. The yield keyword can be used multiple times within a generator function to yield multiple values. Each time the generator function is called, it resumes execution from where it left off, remembering its internal state.

Follow-up 2

What are the benefits of using generators in PHP?

There are several benefits of using generators in PHP:

  1. Memory efficiency: Generators allow you to iterate over a large set of values without needing to create an array in memory. This can greatly reduce memory usage, especially when dealing with large datasets.

  2. Performance improvement: Since generators do not need to generate and store all values upfront, they can start producing values immediately. This can lead to improved performance, especially when dealing with large datasets or when the values are generated on-the-fly.

  3. Simplified code: Generators provide a more concise and readable way to write code that iterates over a set of values. They eliminate the need to manually manage iteration state and provide a more intuitive way to express iteration logic.

Follow-up 3

Can you provide an example of a generator function in PHP?

Sure! Here's an example of a generator function in PHP:

function countUpTo($limit) {
    for ($i = 1; $i <= $limit; $i++) {
        yield $i;
    }
}

$generator = countUpTo(5);

foreach ($generator as $number) {
    echo $number . " ";
}

In this example, the countUpTo function is a generator function that yields numbers from 1 to the specified limit. The generator function is called with a limit of 5, and the returned generator object is iterated over using a foreach loop. Each yielded number is echoed, resulting in the output: 1 2 3 4 5.

2. What are namespaces in PHP and why are they used?

Namespaces in PHP are a way to encapsulate related classes, interfaces, functions, and constants under a named scope, avoiding naming collisions between your code and third-party libraries.

Declaring a namespace:

userService->findOrFail($id);
    }
}

Composer and PSR-4:

"autoload": {
    "psr-4": {
        "App\\": "src/"
    }
}

App\Models\User maps to src/Models/User.php. Running composer dump-autoload registers this mapping so PHP finds class files automatically.

↑ Back to top

Follow-up 1

How do you define a namespace in PHP?

In PHP, you can define a namespace using the namespace keyword followed by the desired namespace name. The namespace declaration should be placed at the top of the PHP file, before any other code or declarations. Here's an example of defining a namespace:

namespace MyNamespace;

Follow-up 2

Can you provide an example of using namespaces in PHP?

Certainly! Here's an example of using namespaces in PHP:

// Define a namespace
namespace MyNamespace;

// Define a class within the namespace
class MyClass {
    public function __construct() {
        echo 'Hello from MyClass!';
    }
}

// Create an instance of the class
$myObject = new MyClass();

Follow-up 3

What is the purpose of the 'use' keyword in relation to namespaces in PHP?

The use keyword in PHP is used to import namespaces or specific elements (such as classes, functions, or constants) from a namespace into the current scope. It allows you to refer to those elements without having to fully qualify their names with the namespace. The use keyword can be used both inside and outside of namespace declarations. Here's an example:

// Import a namespace
use MyNamespace\MyClass;

// Use the imported class
$myObject = new MyClass();

3. How can you use namespaces to avoid name collisions in PHP?

Namespaces prevent collisions by placing your classes in a named scope. Two classes with the same name in different namespaces are completely distinct:

// Your code
namespace App\Http;
class Request { /* ... */ }

// A vendor library
namespace Symfony\Component\HttpFoundation;
class Request { /* ... */ }

// Both can coexist; PHP resolves them by their fully qualified name
$myRequest     = new \App\Http\Request();
$symfonyRequest = new \Symfony\Component\HttpFoundation\Request();

The use statement — importing for convenience:

namespace App\Controllers;

use App\Services\UserService;
use Symfony\Component\HttpFoundation\Request;

class UserController {
    public function index(Request $request): void { ... }
}

Without use, you'd write the full path every time: new \Symfony\Component\HttpFoundation\Request().

Aliasing to resolve conflicts:

use App\Http\Request as AppRequest;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

function handle(AppRequest $app, SymfonyRequest $symfony): void { ... }

Namespace grouping (use declarations, PHP 7.0+):

use App\Models\{User, Post, Comment};
use function App\Helpers\{formatDate, truncate};
use const App\Config\{APP_ENV, DEBUG};

PSR-4 autoloading ties it all together: The composer.json autoload section maps namespace prefixes to directories, so Composer's autoloader resolves any fully-qualified class name to the correct file automatically.

↑ Back to top

Follow-up 1

Can you provide an example of a name collision problem that can be solved using namespaces?

Sure! Let's say you have two PHP libraries, LibraryA and LibraryB, and both libraries define a class called Logger. Without namespaces, if you try to use both libraries in the same project, you will encounter a name collision because both classes have the same name. However, by using namespaces, you can avoid this problem by defining each class under a different namespace. For example:

namespace LibraryA;

class Logger
{
    // Class implementation
}

namespace LibraryB;

class Logger
{
    // Class implementation
}

Follow-up 2

What is the difference between defining functions inside and outside a namespace in PHP?

In PHP, when you define a function outside of a namespace, it is considered to be in the global namespace. This means that the function can be accessed from anywhere in your code without specifying a namespace. On the other hand, when you define a function inside a namespace, it is only accessible within that namespace or from other namespaces that import or use that namespace.

Here's an example to illustrate the difference:

// Function defined outside a namespace
function globalFunction()
{
    // Function implementation
}

namespace MyNamespace;

// Function defined inside a namespace
function localFunction()
{
    // Function implementation
}

4. Can you explain the concept of sub-namespaces in PHP?

Sub-namespaces are namespaces nested within a parent namespace, using backslash (\) as the separator. They allow fine-grained organization of code within a larger namespace hierarchy.

// Top-level namespace
namespace App;

// Sub-namespaces
namespace App\Http\Controllers;
namespace App\Http\Middleware;
namespace App\Database\Repositories;
namespace App\Services\Payment;

Example project structure:

src/
├── Http/
│   ├── Controllers/
│   │   └── UserController.php   → namespace App\Http\Controllers;
│   └── Middleware/
│       └── AuthMiddleware.php   → namespace App\Http\Middleware;
└── Services/
    └── Payment/
        └── StripeService.php    → namespace App\Services\Payment;

Using sub-namespaced classes:

namespace App\Http\Controllers;

use App\Services\Payment\StripeService;
use App\Database\Repositories\UserRepository;

class CheckoutController {
    public function __construct(
        private StripeService $stripe,
        private UserRepository $users,
    ) {}
}

PSR-4 mapping: With Composer, App\\ mapped to src/ means App\Http\Controllers\UserController automatically resolves to src/Http/Controllers/UserController.php. The namespace hierarchy mirrors the directory structure.

Sub-namespaces have no special language behavior beyond being part of the fully-qualified name — they are purely an organizational convention.

↑ Back to top

Follow-up 1

How do you define a sub-namespace in PHP?

To define a sub-namespace in PHP, you simply use the namespace keyword followed by the parent namespace and the sub-namespace separated by a backslash. For example, if you have a parent namespace called MyNamespace, and you want to define a sub-namespace called SubNamespace, you would write:

namespace MyNamespace\SubNamespace;

This creates a sub-namespace SubNamespace within the parent namespace MyNamespace.

Follow-up 2

Can you provide an example of using sub-namespaces in PHP?

Sure! Here's an example of using sub-namespaces in PHP:

namespace MyNamespace;

class MyClass {}

namespace MyNamespace\SubNamespace;

class MySubClass {}

In this example, we have a parent namespace MyNamespace and a sub-namespace SubNamespace. We define a class MyClass within the parent namespace, and a class MySubClass within the sub-namespace. This allows us to organize our code into logical groups and avoid naming conflicts.

5. How do you access global classes, functions, and constants from within a namespace in PHP?

To access a global (non-namespaced) class, function, or constant from within a namespace, prefix its name with a backslash (\):

namespace App\Utils;

class StringHelper {
    public function process(string $input): string {
        // Global class — prefix with \
        $exception = new \InvalidArgumentException('Bad input');

        // Global function — prefix with \
        $length = \strlen($input);
        $encoded = \json_encode(['value' => $input]);

        // Global constant — prefix with \
        $separator = \DIRECTORY_SEPARATOR;
        $pi = \M_PI;

        return $encoded;
    }
}

Why the backslash is needed: Inside a namespace, PHP first looks for the name in the current namespace. Without \, strlen in App\Utils would look for App\Utils\strlen — which doesn't exist — and then fall back to the global scope for functions and constants (but not classes in PHP 7+). Using \ explicitly makes the intent clear and avoids ambiguity.

use as an alternative:

namespace App\Utils;

use InvalidArgumentException;  // import global class
use function strlen;           // import global function
use const DIRECTORY_SEPARATOR; // import global constant

class StringHelper {
    public function validate(string $input): void {
        if (strlen($input) === 0) {
            throw new InvalidArgumentException('Input cannot be empty');
        }
    }
}

Interview note: The global keyword in PHP is unrelated to namespaces — it is used to bring a global variable into function scope (global $db;). To access global namespace members, use the \ prefix or use statements.

↑ Back to top

Follow-up 1

Can you provide an example of accessing a global class from within a namespace?

Sure! Here's an example of accessing a global class MyClass from within a namespace MyNamespace:

namespace MyNamespace;

class AnotherClass {
    public function doSomething() {
        $myObject = new \MyClass();
        // Access the global class
    }
}

Follow-up 2

What happens if you try to access a global function from within a namespace without using the global keyword?

If you try to access a global function from within a namespace without using the global keyword, PHP will look for the function within the current namespace instead of the global scope. If the function is not defined within the namespace, PHP will throw a fatal error.

To access the global function, you need to use the global keyword followed by the function name, or use the fully qualified function name with a leading backslash (\).

Here's an example:

namespace MyNamespace;

function myFunction() {
    echo 'This is a global function.';
}

class AnotherClass {
    public function doSomething() {
        // Access the global function using the global keyword
        global myFunction;
        myFunction();

        // Access the global function using the fully qualified name
        \myFunction();
    }
}

Live mock interview

Mock interview: PHP Generators and Namespaces

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.