我有这两个 WordPress 功能:
$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);
});
但页面返回Notice: Undefined variable: wpb_set_post_views
对于最后一行。
在 PHP 中处理闭包时,您需要确保任何超出范围的变量都放入闭包范围内。这与 JavaScript 不同,JavaScript 中的闭包可以访问 PHP 作用域中声明的变量。
您的匿名函数应如下所示
function() use ($variableNeeded) { }
然后您将可以访问该变量。
重要的是要记住,这是一个按值传递的场景,因此对该变量的任何更改都不会反映在闭包之外,因此您需要按引用传递来进行更改。
function() use (&$variableNeeded) { }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)