May 11, 2012

call back function with $this

Question by v0idless

I am trying to use an instance method as a callback for PHP 5.2.1. I am aware that as of PHP 5.4 you can use $this inside a closure, and in PHP 5.3 you can rename $this to $self and pass that to the closure. However, neither of these methods will suffice since I need this to work for PHP 5.2.1. The two commented lines was my last attempt. That results in Fatal error: Call to a member function hello() on a non-object – is there anyway I can have a callback to an instance method in PHP 5.2.1?

<?php

class Test {

    public function __construct() { 
        $self = &$this;

        $cb = function() use ( $self ) {
            $self->hello();
        };
        call_user_func( $cb );


        // $cb = create_function( '$self', '$self->hello();' );
        // call_user_func( $cb );

    }

    public function hello() {
        echo "Hello, World!n";
    }
}

$t = new Test();

Answer by Rocket Hazmat

$cb = create_function('$self', '$self->hello();');

This is just making a function that can take a parameter called $self. It’s the same as this:

function test($self){
    $self->hello();
}

You can try passing $self (or $this) to the function when you call it:

call_user_func($cb, $this);

You can also try to make $self a global variable, so that the anonymous function made by create_function can read it.

$GLOBALS['mySelf'] = $self;
$cb = create_function('', 'global $mySelf;  $mySelf->hello();');
call_user_func($cb);
// You may want to unset this when done
unset($GLOBALS['mySelf']);

Answer by Starx

How about SIMPLICITY?

class Test {

    public function __construct() { 
        $this -> funcName($this);
    }

    public function funcName($obj) {
            $obj->hello();
    }

    public function hello() {
        echo "Hello, World!n";
    }
}

Update: Just tested the codes. They are working fine using this.

call_user_func_array(array($self, "hello"), array());

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!