【问题标题】:Why doesn't this php function execute?为什么这个 php 函数不执行?
【发布时间】:2016-07-03 22:39:20
【问题描述】:

以下是 php 文档的一部分,带有几个条件。第一个,如果是真的,将一个匿名函数存储在一个变量$the_image_styles 中,几行之后它被成功调用。第二个,如果是真的,将一个匿名函数存储在一个变量$the_overlay_styles 中,该变量随后永远不会执行。

WordPress 输出以下内容:调用未定义函数 the_overlay_styles()

在我看来,这两个声明/调用之间没有区别,但显然情况并非如此。我错过了什么?

<?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: ?>

【问题讨论】:

  • 您正在定义一个 $the_overlay_styles 变量,它引用了一个闭包。要调用它,您可以使用$the_overlay_styles();。但是不要。只需将其定义为普通的 function the_overlay_styles() 即可。
  • 其实这里根本不需要函数,很乱。只需定义一个变量$the_overlay_styles = "background: $banner_colour; opacity: $banner_opacity";,然后再定义一个echo $the_overlay_styles。
  • @jszobody - 啊,我错过了一个 $ 符号,这并没有完全帮助。但是,是的,您的建议不那么复杂。谢谢。
  • 你可以试试这个:&lt;div style="&lt;?php echo $the_overlay_styles(); ?&gt;"&gt;&lt;/div&gt; 没有$,你调用的是function,而不是the_overlay_styles,而不是variable
  • @verism 很高兴为您提供帮助。我将此作为答案发布在下面,以便您接受。

标签: php wordpress scope closures


【解决方案1】:

您正在定义一个$the_overlay_styles variable,它引用了一个闭包。要调用它,您可以使用$the_overlay_styles();。

但不要。只需将其定义为普通函数即可:

function the_overlay_styles() {

你知道吗,甚至不要那样做。只需在这里创建一个变量!远不那么混乱。

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

现在您可以在需要时直接echo $the_overlay_styles。

【讨论】:

    【解决方案2】:

    在这样的函数调用之前添加一个 $

    <div style="<?php $the_overlay_styles(); ?>"></div> <<-- This call never executes
    

    函数声明相同,但函数调用不同。

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2011-01-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多