Reputation: 1164
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: ?>
Upvotes: 0
Views: 61
Reputation: 910
Add a $ before function call like this
<div style="<?php $the_overlay_styles(); ?>"></div> <<-- This call never executes
The functions declaration is the same but the function calls are different.
Upvotes: 0
Reputation: 28941
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.
Upvotes: 1