I touched on this in the last article: "Looking at PHP's OOP from a CFMLer's perspective: overloading (which is not what you'd assume it is)". PHP has a magic constant
__FUNCTION__ which returns the name of the function being called. I claimed it's kinda like getFunctionCalledName() in CFML. But not quite. Let's have a look.(This will be a pretty short article, I think).
CFML: getFunctionCalledName()
As a recap, here's some CFML code demonstrating getFunctionCalledName():// getFunctionCalledName.cfm
function f(){
echo("#getFunctionCalledName()#() called<br>");
}
f();
echo("<hr>");
g = f;
g();
This outputs:
F() calledG() called
Note that despite the function being declared as
f(), getFunctionCalledName() "knows" the latter call to it was via the reference g. OK. That's the baseline expectation set.
PHP equivalent: __function__?
(Betteridge alert!)Here's the equivalent PHP code using
__function__:<?php
// testFunction.php
function f()
{
echo sprintf("Using __FUNCTION__: %s() called<br>", __FUNCTION__);
}
f();
echo "<hr>";
$g = "f";
$g();
And this outputs:
Using __FUNCTION__: f() calledUsing __FUNCTION__: f() called
Hmmm. So
__FUNCTION__ always returns the function with its defined name.On a whim, let's see what happens with a function expression:
<?php
// testFunctionExpression.php
$f = function () {
echo sprintf("Using __FUNCTION__: %s() called<br>", __FUNCTION__);
};
$f();
echo "<hr>";
$g = $f;
$g();
Result:
Using __FUNCTION__: {closure}() calledUsing __FUNCTION__: {closure}() called
"closure". Harrumph. But anyway, that's along the lines of what I expected. Pleasingly, the syntax for a function expression is the same as CFML, so I was able to correctly guess that. Win.
debug_backtrace()?
So how do we find the actual name the function was called with?Googling about I found a lot of references to
debug_backtrace(), which is worth looking at:<?php
// debugBackTraceDump.php
require "../../debug/dBug.php";
function f()
{
new dBug(debug_backtrace());
}
f();
echo "<hr>";
$g = "f";
$g();
Result:| debug_backtrace() (array) | |||||||||||||
| 0 |
| ||||||||||||
| debug_backtrace() (array) | |||||||||||||
| 0 |
| ||||||||||||
Well it's handy to know about
debug_backtrace(), but it's no help to us here.Nope
More googling... and I've drawn a blank.Maybe I have to pop my head above the parapet on Stack Overflow and ask a question? Shudder. Done: "PHP: Get the name a function was called as, equivalent to CFML's getFunctionCalledName()".
--
Adam