How to use $this in Anonymous Function in PHP 5.3

Yesterday I wrote a WordPress Login Notification Plugin. And I use Anonymous Function (introduced in PHP 5.3) in the settings. It work well in my server but when I install it in my client site, the settings page is truncated even though my client use PHP 5.3.

settings-page-truncatedAfter some googling, I found that we cannot use $this in anonymous function in PHP 5.3, we can use that only in PHP 5.4 +. Thank god I didn’t get fatal error 🙂

How to solve this?

/**
 * Only in PHP 5.4
 * Cannot do this in PHP 5.3
 */
class my_Class_Something{

    public $my_var = 'my_var';

    public function __construct(){
        add_action(
            'some_hook',
            function(){
                return $this->my_var;
            }
        );
    }
}

Well, actually we still can’t use $this (directly in anonymous function), but we can do something like this:

/**
 * PHP 5.3 Workaround
 */
class my_Class_Something{

    public $my_var = 'my_var';

    public function __construct(){
        $var = $this->my_var;
        add_action(
            'some_hook',
            function() use( $var ){
                return $var;
            }
        );
    }
}

note: in the end, i decided to not use anonymous function at all. so the plugin is PHP 5.2 compatible 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *