0

How can we declare the function name dynamically?

For example :

$function = 'test'
public $function(){

}
PaladiN
  • 4,625
  • 8
  • 41
  • 66
soussou
  • 41
  • 6
  • 1
    Why should you be interested in the _name_ of a dynamic function? That makes no sense, since you never call it my its name. The example you give does _not_ attempt to define a dynamic function at all, but an ordinary global function. – arkascha Jan 17 '17 at 12:05
  • Call a function from a variable may be. – Sougata Bose Jan 17 '17 at 12:07
  • @SougataBose For that you want to store a dynamic function ("lambda function") inside a variable. That does not change the _name_ of a function, but only it's scope. – arkascha Jan 17 '17 at 12:13
  • i am interested to dynamic function , because i have to generate relation functions in yii2 model , these functoins change whene the model change . So it should be dynamic. Please read my post here : http://stackoverflow.com/questions/41693837/advanced-yii2-application-function-to-generate-relation-model-dynamically-with – soussou Jan 17 '17 at 12:14
  • @arkascha, I meant - `function a() {echo 'hi';}; $a = 'a'; $a();` – Sougata Bose Jan 17 '17 at 12:16
  • @SougataBose Sure, I understood that. But still that does _not_ change the functions name as the OP asks. – arkascha Jan 17 '17 at 12:19
  • Yes that does not. I am just sure why OP want to do that. I was just wandering. :) – Sougata Bose Jan 17 '17 at 12:21

2 Answers2

0

You could use a callback for this:

https://stackoverflow.com/a/2523807/3887342

function doIt($callback) { $callback(); }

doIt(function() {
    // this will be done
});
Community
  • 1
  • 1
PaladiN
  • 4,625
  • 8
  • 41
  • 66
0

Declaring a function with a variable but arbitrary name like this is not possible without getting your hands dirty with eval() or include().

I think based on what you're trying to do, you'll want to store an anonymous function in that variable instead (use create_function() if you're not on PHP 5.3+):

$variableA = function() {
    // Do stuff
};

You can still call it as you would any variable function, like so:

$variableA();
Arda Kazancı
  • 8,341
  • 4
  • 28
  • 50