Leaving out a long story, I have a scenario like this:
class Foo {
function doSomething() {
print "I was just called from " . debug_backtrace()[1]['function'];
}
function triggerDoSomething()
{
// This outputs "I was just called from triggerDoSomething".
// This output makes me happy.
$this->doSomething();
}
function __call($method, $args)
{
// This way outputs "I was just called from __call"
// I need it to be "I was just called from " . $method
$this->doSomething();
// This way outputs "I was just called from {closure}"
// Also not what I need.
$c = function() { $this->doSomething() };
$c();
// This causes an infinite loop
$this->$method = function() { $this->doSomething() };
$this->$method();
}
}
In the case that I call $foo->randomFunction(), I need the the output to read "I was just called from randomFunction"
Is there a way to name a closure or approach this problem differently?
Note: I cannot change the doSomething function. It is a sample of third-party code I'm calling that considers the function name of who called it in order to do something.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
Lexical scoping, also known as static scoping, is a convention used with many modern programming languages. It refers to setting the scope, or range of functionality, of a variable so that it may be called (referenced) from within the block of code in which it is defined.
Closures help in maintaining the state between function calls without using a global variable.
Disadvantages of closures There are two main disadvantages of overusing closures: The variables declared inside a closure are not garbage collected. Too many closures can slow down your application. This is actually caused by duplication of code in the memory.
you can pass the name to doSomething()
like
$this->doSomething($method);
or with closure like
$c = function($func_name) { $this->doSomething($func_name); };
$c($method);
and in doSomething
you can use that parameter.
function doSomething($method) {
print "I was just called from " . $method;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With