marcelo2605
marcelo2605

Reputation: 2794

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.

Upvotes: 4

Views: 1058

Answers (2)

user3535945
user3535945

Reputation: 241

Use global keyword to access the outside variables in a function.

So your code will be

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

Or

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 = $GLOBALS['wpb_set_post_views'];
        $wpb_set_post_views($post_id);
    });

Please refer http://php.net/manual/en/language.variables.scope.php

Upvotes: 0

Zarathuztra
Zarathuztra

Reputation: 3251

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) { }

Upvotes: 10

Related Questions