PHP Anonymous Functions Example Implementation
In PHP, an anonymous method is usually referred to as an anonymous function or a closure. These are functions defined without a name, and they're often used as callbacks or for short-term use.
Here are a few example usages of anonymous methods (closures) in PHP:
- Assign to a Variable
$greet = function($name) {return "Hello, $name!";};echo $greet("Mike"); // Output: Hello, Mike! - Use as Callback (e.g., array_map)
$numbers = [1, 2, 3, 4];$squared = array_map(function($n) { return $n * $n; }, $numbers);print_r($squared); // Output: [1, 4, 9, 16] - Use with use to Capture Variables from Parent Scope
$multiplier = 5;$multiply = function($n) use ($multiplier) {return $n * $multiplier;};echo $multiply(10); // Output: 50 - Inside of a Class as a Property
class Greeter {
public $greet;
public function __construct() {
$this->greet = function($name) {
return "Hi, $name!";
};
}
}
$greeter = new Greeter();
echo ($greeter->greet)("Ralph"); // Output: Hi, Ralph!
Remember to wrap class and property inside of parentheses. It's necessary in that specific form because $greeter->greet is a property that holds a closure, not a method. PHP interprets $greeter->greet("Taylor") as trying to call a method named greet, not a closure stored in a property.
5. Anonymous Method Bound to Object (Closure::bind)
class Person { private $name = "Secret Name";}$getName = function() {return $this->name;};$person = new Person();$bound = $getName->bindTo($person, 'Person');echo $bound(); // Output: Secret Name
If you would like more examples or have a question please shoot me a comment. Thanks!