You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP7.2中create_function()已废弃,如何修正对应add_filter代码消除错误?

Fixing "Deprecated: Function create_function() is deprecated" in PHP 7.2+

Hey there, that deprecation warning is super common when working with older PHP code—let's get rid of it while keeping your functionality totally intact.

The Problem

create_function() got deprecated in PHP 7.2 for good reasons: it's prone to code injection risks (since it builds functions via string manipulation) and is far less flexible than modern PHP features. Your original code uses it to create a simple callback for the filter:

add_filter( 'option_page_capability_' . ot_options_id(), create_function( '$caps', "return '$caps';" ), 999 );

The Fix: Use an Anonymous Function (Closure)

PHP 5.3+ supports native anonymous functions (closures), which are the perfect drop-in replacement here. They're safer, cleaner, and won't trigger deprecation warnings. Here's your updated code:

add_filter( 'option_page_capability_' . ot_options_id(), function( $caps ) {
    return $caps;
}, 999 );

What Changed?

  • We swapped out the create_function() call for a native anonymous function. The core logic stays identical: it accepts the $caps parameter and returns it right back, so your filter behaves exactly as it did before.
  • Unlike create_function(), closures don't rely on string parsing—this eliminates injection risks and makes the code easier to read and modify later on.

If you ever need to reference external variables in the callback down the line, you can use the use() keyword to pull them into the closure's scope (here's a quick example):

$custom_cap = 'manage_options';
add_filter( 'option_page_capability_' . ot_options_id(), function( $caps ) use ( $custom_cap ) {
    return $custom_cap;
}, 999 );

内容的提问来源于stack exchange,提问作者Денис Линник

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:08:21