Programming Languages
PHP
Subjective
Sep 23, 2025
What is the output of this PHP 8+ code involving anonymous classes and closures? Explain the scope and binding behavior.
Detailed Explanation
Code Analysis:
$multiplier = 10;
$calculator = new class($multiplier) {
private $factor;
public function __construct($factor) {
$this->factor = $factor;
}
public function createMultiplier() {
return function($value) {
return $value * $this->factor;
};
}
public function createStaticMultiplier() {
$factor = $this->factor;
return static function($value) use ($factor) {
return $value * $factor;
};
}
};
$multiply1 = $calculator->createMultiplier();
$multiply2 = $calculator->createStaticMultiplier();
echo $multiply1(5) . "\n";
echo $multiply2(5) . "\n";
// Serialize test
try {
serialize($multiply1);
echo "multiply1 serializable\n";
} catch (Exception $e) {
echo "multiply1 not serializable\n";
}
try {
serialize($multiply2);
echo "multiply2 serializable\n";
} catch (Exception $e) {
echo "multiply2 not serializable\n";
}
Output:
50
50
multiply1 not serializable
multiply2 serializable
Explanation:
1. Anonymous Class Behavior:
- Anonymous class captures $multiplier in constructor
- Creates instance with private $factor = 10
- Class has unique generated name like class@anonymous
2. Closure Binding:
- createMultiplier(): Returns non-static closure bound to $this
- createStaticMultiplier(): Returns static closure with captured variable
- Both access the same value but through different mechanisms
3. Serialization Behavior:
- $multiply1: Cannot serialize - bound to object instance
- $multiply2: Can serialize - static closure with captured variables
Advanced Closure Concepts:
// Closure binding manipulation
$closure = function() {
return $this->factor;
};
// Bind to different object
$boundClosure = $closure->bindTo($calculator, $calculator);
echo $boundClosure(); // 10
// Static binding
$staticClosure = Closure::bind($closure, null, get_class($calculator));
// $staticClosure(); // Error: $this not available in static context
Performance Considerations:
- Object-bound closures keep object in memory
- Static closures are more memory efficient
- Use static closures when $this is not needed
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts