Jump to content

Can you define a function's name with a variable?


stompeers

Recommended Posts

Hi folks!

 

This is my first post in PHP Freaks, I hope it's up to snuff. ;)

 

Does anyone know if you can define a function name using a variable? For example:

 

$var = 'my_function_name';

function $var() {
}

 

I know you can't do that verbatim, as I've tried, but I was wondering if there is some workaround that would be valid?

 

Thanks!

Chris

Thanks, I know that one is possible, but you still have to define the function knowing the function's name. I would like to define a function dynamically,without first knowing it's name. Is there any way to do that?

 

Thanks!

Chris

Don't limit his options, he wants what he wants :)

 

I'm not limiting his options, I'm actually trying to do the opposite. I'm trying to figure out why in the world they would want to do that as I can't think of a single reason, and then maybe I can direct them to a better method.

Don't limit his options, he wants what he wants :)

 

I'm not limiting his options, I'm actually trying to do the opposite. I'm trying to figure out why in the world they would want to do that as I can't think of a single reason, and then maybe I can direct them to a better method.

 

yah meeeen im with you why would you waste your time in worthless things like this  ..

You can create functions without a name with create_function().

 

But for what you want you will need eval():

 

$newfunc = 'function foo() { print "foo\n"; }';
eval($newfunc);
foo();

 

That still creates the function with a known name ahead of time... I think he wants (if this even works... lol)

 

$someVar = 'someName';
$newfunc = 'function' . $someVar . '() { print "foo\n"; }';
eval($newfunc);
$someVar();

 

Now I have to go test that... haha

 

PhREEEk

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.