Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faking a closure's function name

Tags:

closures

php

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.

like image 875
Anthony Avatar asked Dec 15 '14 05:12

Anthony


People also ask

What is closure give an example?

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.

What is lexical scoping?

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.

What is the use of closures?

Closures help in maintaining the state between function calls without using a global variable.

What is disadvantage closure?

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.


1 Answers

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;
}
like image 119
bansi Avatar answered Oct 02 '22 01:10

bansi