Current Location: Home> Latest Articles> Essential Advanced PHP Interview Skills: Magic Methods, Generators, and Closures Explained

Essential Advanced PHP Interview Skills: Magic Methods, Generators, and Closures Explained

M66 2025-08-06

Magic Methods

Magic methods allow automatic handling of specific events within a class. For example, __construct() initializes an object, and __destruct() releases resources.

class MyClass {
    public function __construct() {
        // Object initialization code
    }

    public function __destruct() {
        // Cleanup code
    }
}

Generators

Generators provide an efficient way to iterate over large datasets without loading the entire collection at once.

function numbers() {
    for ($i = 0; $i < 10; $i++) {
        yield $i;
    }
}

foreach (numbers() as $number) {
    echo $number;
}

Closures

Closures are anonymous functions that can be passed as arguments and bind variables or objects, enhancing code flexibility.

$greeting = function($name) {
    return "Hello, $name!";
};

echo $greeting("John");

Anonymous Classes

Anonymous classes allow quick creation of classes without naming them, simplifying code structure.

$object = new class {
    public function greet($name) {
        return "Hello, $name!";
    }
};

echo $object->greet("Jane");

Traits

Traits enable adding methods and properties to existing classes without inheritance, improving code reuse.

trait Greeting {
    public function greet($name) {
        return "Hello, $name!";
    }
}

class MyClass {
    use Greeting;
}

$object = new MyClass();
echo $object->greet("Alice");

Practical Example: Creating a Paginator with Generators

This example demonstrates using generators to implement a paginator that fetches data in batches, improving memory efficiency.

function paginate($data, $perPage) {
    $currentPage = 1;
    while ($currentPage <= ceil(count($data) / $perPage)) {
        $offset = ($currentPage - 1) * $perPage;
        yield array_slice($data, $offset, $perPage);
        $currentPage++;
    }
}

$data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

foreach (paginate($data, 3) as $page) {
    print_r($page);
}

The above content covers essential advanced PHP skills frequently asked in interviews. Mastering these topics will help you better tackle interview challenges and improve your development efficiency.