Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Anonymous functions: undefined variable

I'm having these two WordPress functions:

$wpb_set_post_views = function($postID) {
    $count_key = 'wpb_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
};

add_action( 'wp_head', function ($post_id) {
    if ( !is_single() ) return;
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;
    }
    $wpb_set_post_views($post_id);
});

But the page return Notice: Undefined variable: wpb_set_post_views for the last line.

like image 642
marcelo2605 Avatar asked Aug 31 '25 18:08

marcelo2605


1 Answers

When dealing with Closures in PHP you need to ensure that any out of scope variable is put into the Closure scope. This is unlike JavaScript where closures have access to variables declared in a PHP scope.

Your anonymous function should be as follows

function() use ($variableNeeded) { }

You will then have access to that variable.

It is important to keep in mind that this is a pass by value scenario, so any changes to that variable will not be reflected outside the closure, so you would need to pass by reference to make changes.

function() use (&$variableNeeded) { }
like image 69
Zarathuztra Avatar answered Sep 02 '25 07:09

Zarathuztra