Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a function dynamically?

Tags:

function

php

I have a variable like $string = "blah";

How can I create a function that has the variable value as name? Is this possible in PHP?

Like function $string($args){ ... } or something, and be able to call it like:

blah($args);
like image 702
Alex Avatar asked Dec 18 '11 02:12

Alex


People also ask

How do you create a dynamic function?

Creating The Dynamic Function The Function object can also be used as a constructor function to create a new function on the fly. The syntax for creating a function from Function Object is as follows: const myFunction = new Function(arg1, arg2, … argN, body);

How do you create a dynamic function in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.

What is dynamic function example?

Dynamic function is a way of dynamically invoking a function call. The compiler will have limited knowledge of what you are up to so you will get run time errors if you don't use correct inputs and outputs. One example that runs different functions depending on user input: DEFINE VARIABLE iFunc AS INTEGER NO-UNDO.

What is a dynamic function in JavaScript?

The dynamic nature of JavaScript means that a function is able to not only call itself, but define itself, and even redefine itself. This is done by assigning an anonymous function to a variable that has the same name as the function.


2 Answers

this might not be a good idea, but you can do something like this:

$string = "blah";
$args = "args"
$string = 'function ' . $string . "({$args}) { ... }";
eval($string);
like image 78
fardjad Avatar answered Oct 23 '22 02:10

fardjad


That doesn't sound like a great design choice, it might be worth rethinking it, but...

If you're using PHP 5.3 you could use an anonymous function.

<?php
$functionName = "doStuff";
$$functionName = function($args) {
    // Do stuff
};

$args = array();
$doStuff($args);
?>
like image 38
Richard John Avatar answered Oct 23 '22 01:10

Richard John