0

actually I wish to create a function which combine all similar functions with similar function name. For example,

<?php
//this function carry the function name I wish to create. For example:function try
a("try");


function a($arg)
{
  //I wish to create function with the name carried by $arg
  //but function $arg won't work
}
?>

Anyone can guide me regarding such function?

Song
  • 1
  • 1
  • 1
    Can you elaborate why you want to do this? This smells of broken design, I'm sure there is a better way to achieve what you want – Pekka Sep 12 '11 at 10:05
  • Do you mean you are after a line that will call function b? In which case you want variable variables $$arg, but I'd agree with @Pekka that there will be a better way. – Jonnix Sep 12 '11 at 10:08
  • (ref) [create_function](http://php.net/manual/function.create-function.php) – Yoshi Sep 12 '11 at 10:15
  • @Song - What's the function supposed to do anyway? – Álvaro González Sep 12 '11 at 10:22

1 Answers1

1

PHP is able to use variables as call-time function names so all you would have to do is

function a($arg)
{
    if (!function_exists($arg)) {
        throw new InvalidArgumentException(
            sprintf('"%s" is not a valid function', $arg));
    }
    $arg();
}

If you must go down the functional path, you should do it properly

function a(Closure $callback)
{
    $callback();
}

a(function() {
    echo 'This is a callback';
});

or even

$b = function() {
    echo 'I am an anonymous function';
};

a($b);

See http://php.net/manual/en/functions.anonymous.php

Phil
  • 157,677
  • 23
  • 242
  • 245
  • As far as I know, you can use variable variables to *call* existing functions but not to *create* them, unless you use [eval()](http://es.php.net/eval) which, needless to say, is the fastest way to produce insecure and hard to maintain code. [It can probably be done with class methods](http://es.php.net/__call), though. However, the main issue is: create functions that do *what*? – Álvaro González Sep 12 '11 at 10:25
  • @Álvaro I may have misunderstood the question – Phil Sep 12 '11 at 10:27
  • Well, the question is hard to understand :) But your answer is nice anyway. – Álvaro González Sep 12 '11 at 10:43
  • Actually, I done this in order to enhance my own wordpress function. As currently, I am using add_action( 'init', 'function_name' ); for every function of different name, so I considered to create a basic function to change the name of the function I use in the wordpress function. – Song Sep 13 '11 at 04:17