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

如何将类中带条件分支的可变参数printf合并为单个调用?是否需优化?

Merging Conditional printf Calls into One

Absolutely, you can clean this up into a single formatted output call while keeping it maintainable. The key is to build your format string and arguments dynamically based on the $add_info flag, which eliminates the duplicate code in your original branches.

Here's a streamlined implementation:

// Precompute common values to avoid repetition
$field_attr = esc_attr($field);
$checked = isset($this->options[$field]) && (1 == $this->options[$field]) ? 'checked="checked" ' : '';
$descr = __($this->settings_list[$field]['descr'], 'extra-settings-for-woocommerce');
$info = __($this->settings_list[$field]['info'], 'extra-settings-for-woocommerce');

// Build the base format string
$format = '<fieldset> <label><input id="%1$s" type="checkbox" name="eswc_settingz[%1$s]" value="1" %2$s />%3$s</label> </fieldset>';

// Append the optional description section if needed
if ($add_info) {
    $format .= ' <p class="description">%4$s</p>';
}

// Assemble the arguments array
$args = [$field_attr, $checked, $descr];
if ($add_info) {
    $args[] = $info;
}

// Use vprintf to handle variable argument count
vprintf($format, $args);

Why this works:

  • DRY Code: We eliminate the duplicate long format string and repeated calculations (like the checked ternary) from your original if/else branches.
  • Dynamic Construction: The format string and arguments array are built only once, with the optional parts added conditionally.
  • vprintf instead of printf: This function accepts an array of arguments, which lets us easily add or remove the extra %4$s argument when needed.

Is the original code "good enough"?

Your original code functions correctly, but it has redundant code that makes it harder to maintain. If you ever need to update the fieldset/label structure, you'd have to change it in two places instead of one. The optimized version fixes that without adding unnecessary complexity.

内容的提问来源于stack exchange,提问作者Ryszard Jędraszyk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:48:19