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

Link to comment
Share on other sites

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  ..

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.