Reputation: 29870
Here is an example of the CFML code I am using as a baseline (also on github @ getFunctionCalledName.cfm):
function f(){
echo("#getFunctionCalledName()#() called<br>");
}
f();
echo("<hr>");
g = f;
g();
This outputs:
F() called
G() called
Note that getFunctionCalledName()
returns the name of the reference used to call the function, not simply the name of the function.
I'm trying to see if there's an equivalent in PHP. Here's my test of that (testFunction.php on GitHub):
I know there's the __FUNCTION__
magic constant:
function f()
{
echo sprintf("Using __FUNCTION__: %s() called<br>", __FUNCTION__);
}
f();
echo "<hr>";
$g = "f"; // as someone points out below, this is perhaps not analogous to the g = f in the CFML code above. I dunno how to simply make a new reference to a function (other than via using function expressions instead, which is not the same situation
$g();
However this returns f
in both cases.
I've written similar code trying debug_backtrace()
(see testDebugBackTrace.php), but that also references the function as f
.
This is fine, and I understand why they both do that. However I'm wondering if there's any PHP equivalent of getFunctionCalledName()
. I hasten to add this is just for an exploratory exercise: I am currently migrating myself from CFML to PHP and this just came up when I was demonstrating something on my blog.
Upvotes: 3
Views: 141
Reputation: 806
I don't think what you're after is possible in PHP without something like the runkit extension. That has the functionality to create a copy of a function under a new name. I haven't tried this out myself as I couldn't find a Windows version of the extension.
http://php.net/manual/en/function.runkit-function-copy.php
<?php
function f() {
echo sprintf("Using __FUNCTION__: %s() called<br>", __FUNCTION__);
}
runkit_function_copy('f', 'g');
f();
g();
?>
Upvotes: 0
Reputation: 2116
Your code $g = "f";
isn't really copying the function to another variable, it's just creating a string reference to the same function. The following would be more analogous to the CFML you provide:
$x = function() {
echo __FUNCTION__;
};
$v = $x;
$v();
The above code just outputs {closure}
, since PHP doesn't assign a formal name to anonymous functions. So, the answer is, no, it isn't possible in PHP.
Upvotes: 1