note 84422 deleted from language.constants by danbrown

From: Date: Fri, 12 Jun 2009 22:18:00 +0000
Subject: note 84422 deleted from language.constants by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-156821@lists.php.net to get a copy of this message
Note Submitter: seth36 at gmail dot com ---- Follow up to last note - After trying this out it seems that ${CFUNC}(); will not work either, however a constant can be used as a reference to a function when used with call_user_func(). The example below is based of ian's original to explain this: <?php function A() { echo "<p>I am function A from \$Variable reference</p>\n"; } function B() { echo "<p>I am function B from CONSTANT reference</p>\n"; } $FunctionA = "A"; define("FUNCTIONB", "B"); /* // #Works - $FunctionA evaluates to "A" and calls corresponding function // Returns - I am function A from $Variable reference */ $FunctionA(); /* // #Fails - PHP considers FUNCTIONB() a call to user defined "FUNCTIONB", function doesn't exist so PHP throws an error - this IS correct behaviour! // Returns - Fatal error: Call to undefined function: functionb() in... */ FUNCTIONB(); /* // #Works - $FunctionA variable is passed as string "A" to call_user_func() // Returns - I am function A from $Variable reference */ call_user_func($FunctionA); /* // #Works - FUNCTIONB constant is passed as string "B" to call_user_func() // Returns - I am function B from CONSTANT reference */ call_user_func(FUNCTIONB); ?> Again though why anyone would need / want a constant as a reference to a function escapes me. The function itself has to have the same name as the value of the constant that will refer to it, therefore there's no reason you can't simply call the function normally, infact it's probably better to do so as using a constant for this ensures the following: 1.) A call to define() is required to set the constant 2.) The constant will need it's value determined (as a string) when being passed to call_user_func() 3.) Two functions must be called whenever you call a function in this manner - call_user_func() and the target function. That's more memory used up in your application, whereas calling the function directly avoids this entirely. My opinion is to forget about constants as function references - use variable functions or call the function directly and keep constants for any fixed parameters you need globally available.

« previous php.notes (#156821) next »