【发布时间】: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 - 啊,我错过了一个 $ 符号,这并没有完全帮助。但是,是的,您的建议不那么复杂。谢谢。
-
你可以试试这个:
<div style="<?php echo $the_overlay_styles(); ?>"></div>没有$,你调用的是function,而不是the_overlay_styles,而不是variable -
@verism 很高兴为您提供帮助。我将此作为答案发布在下面,以便您接受。
标签: php wordpress scope closures