Reputation: 56351
I want to define one function, but with two different names. I can achieve that such:
function my1($a, $b) { ...... }
function my2($a, $b) { my1($a,$b); }
but I am interested, if there is a shorter way, like:
function my1 & my2 ($a, $b) { ...... }
Upvotes: 2
Views: 783
Reputation: 391
You can make a recursive function instead of creating two same function. For example:
function my1($a, $b, $is_recursive = false) {
...
if ($is_recursive) {
my1($a, $b, false);
}
}
Upvotes: 0
Reputation: 1907
Yes! for that you need to use anonymous functions. One variable hold your function and another variable refer to same variable.
<?php
// Define function
$say_hello_1 = function ()
{
echo "Hello";
};
// Refer to same function with different name
$say_hello_2 = $say_hello_1;
// Call to both of them
$say_hello_2();
$say_hello_1();
Both of call represent same function and print Hello twice.
Upvotes: 0
Reputation: 2137
try anonymous functions. It allows you to call the same function but with different names. like so
<?php
$function_1 = $function_2 = function($a,$b){ //The anonymous function is assigned names $function_1 & $function_2.
echo $a.' - '.$b;
};
$function_1('a','b');
$function_2('1','2');
?>
Read the complete reference here
Upvotes: 6