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();
This is just making a function that can take a parameter called
$self. It’s the same as this:You can try passing
$self(or$this) to the function when you call it:You can also try to make
$selfa global variable, so that the anonymous function made bycreate_functioncan read it.