duanchun1852 2016-03-17 14:07
浏览 22
已采纳

为什么这个php函数不执行?

The following is a section of a php document, with a couple of conditionals. The first, if truthy, stores an anonymous function in a variable $the_image_styles, which is successfully called a few lines later. The second, if truthy, store an anonymous function in a variable $the_overlay_styles, which never subsequently executes.

WordPress outputs the following: Call to undefined function the_overlay_styles()

It appears to me there's no difference between the two declarations/invocations, but clearly that's not the case. What am I missing?

<?php
$banner = get_field('banner_image');
// Check for image
if ($banner) :
    $xpos = get_field('banner_xpos');
    $ypos = get_field('banner_ypos');
    // Style string for background image
    $the_image_styles = function() use ($banner, $xpos, $ypos){
        echo "background-image:url({$banner['sizes']['large']}); background-position:{$xpos} {$ypos}";
    };
    // Check for overlay, for later use
    $has_overlay = get_field('has_banner_overlay');
?>

    <!-- Article header with banner -->
    <header style="<?php $the_image_styles(); ?>"> <<-- This function call works

        <?php
        if ($has_overlay) :
            $banner_colour  = get_field('banner_colour');
            $banner_opacity = number_format( get_field('banner_opacity') / 100, 2 );
            // Style string for imageoverlay
            $the_overlay_styles = function() use ($banner_colour, $banner_opacity){
                echo "background:{$banner_colour}; opacity:{$banner_opacity}";
            };
        ?>

        <div style="<?php the_overlay_styles(); ?>"></div> <<-- This call never executes
        <?php endif; ?>
        <h1><?php the_title(); ?></h1>
    </header>


<?php else: ?>
  • 写回答

2条回答 默认 最新

  • doucitao2944 2016-03-17 14:17
    关注

    You're defining a $the_overlay_styles variable, which references a closure. To call that, you'd do $the_overlay_styles();.

    But don't. Just define it like a normal function to begin with:

    function the_overlay_styles() {
    

    You know what though, don't even do that. Just create a variable here! Far less messy.

    $the_overlay_styles = "background: $banner_colour; opacity: $banner_opacity";
    

    Now you can just echo $the_overlay_styles when you need it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号