user4096537
user4096537

Reputation:

How can I find out the classname of an object a closure is bound to?

I've some third party code that creates a closure which gets afterwards bound to an object. A print_r on the closure object yields this:

Closure Object ( [this] => am4Widgets Object ( ) )

Now I need to retrieve the 'instanceof' of the bound object (in this case 'am4Widgets'), some kind of pseudocode like

print_r(myClosureObject instanceofboundobject am4Widgets);

which should output 'TRUE'.

I've searched php.net but to no avail.

Thanks in advance for any idea/suggestion.

UPDATE:

Here is where the closure is created (snippet of code that I cannot modify):

function initActions()
{
    parent::initActions();
    .
    .
    .
    add_action('wp_head', function(){
        $ajax_url =  admin_url( 'admin-ajax.php' );
        echo <<<CUT
<script>...some javascript code...</script>
CUT;
    });
}

Actually, what I'm try to do is to unhook the closure from wp_head because I need it in the footer.

I'm using the global wordpress' $wp_filters to access all registered hook, but now I need a way to uniquely identify the closure I want to unhook, which could be an easy task if there was a way to access the closure's bound object.

Upvotes: 3

Views: 411

Answers (1)

German Lashevich
German Lashevich

Reputation: 2453

You can use ReflectionFunction object for that purpose.

class A {}

$closure = (function () {
    echo '$this class from closure: ' . get_class($this) . "\n";
})->bindTo(new A());

$closure();

$fn = new ReflectionFunction($closure);
echo '$this class from reflection: ' . get_class($fn->getClosureThis());

Output:

$this from closure: A
$this from reflection: A

Upvotes: 5

Related Questions