gpt4 book ai didi

PHP匿名函数: undefined variable

转载 作者:行者123 更新时间:2023-12-05 01:02:37 24 4
gpt4 key购买 nike

我有这两个 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);
});

但页面返回 注意: undefined variable :wpb_set_post_views 最后一行。

最佳答案

在 PHP 中处理闭包时,您需要确保将任何超出范围的变量放入闭包范围。这与 JavaScript 不同,在 JavaScript 中,闭包可以访问 PHP 范围内声明的变量。

你的匿名函数应该如下

function() use ($variableNeeded) { }

然后您将可以访问该变量。

请务必记住,这是按值传递的场景,因此对该变量的任何更改都不会反射(reflect)在闭包之外,因此您需要通过引用进行更改。

function() use (&$variableNeeded) { }

关于PHP匿名函数: undefined variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32441301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com