为什么将一个PHP函数分配给一个变量执行它?
我在WordPress使用这个:为什么将一个PHP函数分配给一个变量执行它?
<?php if (!is_front_page()) {
$title = the_title();
echo <<<EOT
<div class="featured-header col-xs-12 col-sm-12 col-md-12 col-lg-12 cf">
<span class="featured-title">$title</span>
</div>
EOT;
} ?>
然而,由PHP股利前生成的页面标题。它看起来像$ title变量本身的声明执行the_title()
函数。
这是为什么?
编辑:
感谢您的解释!这是现在的工作代码:
<?php if (!is_front_page()) {
$title = get_the_title();
$thumbnail = get_the_post_thumbnail_url();
echo <<<EOT
<div class="featured-header col-xs-12 col-sm-12 col-md-12 col-lg-12 cf" style="background-image: url('$thumbnail');">
<span class="featured-title animated fadeIn">$title</span>
</div>
EOT;
} ?>
the_title()
是一个模板函数显示(echo
)的标题。如果要将标题存储在var中,请改用get_the_title()
。
注意,大多数的WP模板函数的工作是这样的:get_the_content()
VS the_content()
,get_the_date()
VS the_date()
...
谢谢,这工作! – Andrew
的the_title()
功能被执行,因为你叫它。返回值存储在$title
变量中,之后不会更改。
我不知道该功能是干什么的。 也许它回响了一些东西,并没有返回 - 那么回显值将被打印出来,而不是存储在变量中,你无法做任何事情。
如果返回的东西,不附和,那么你可以这样做:
$heredoc = <<<EOT
<div class="featured-header col-xs-12 col-sm-12 col-md-12 col-lg-12 cf">
<span class="featured-title">%t</span>
</div>
EOT;
$heredoc = sprintf($heredoc, the_title());
echo $heredoc;
写作$title = the_title()
实际调用的函数,然后将返回的值,这是正常现象,在所有的编程语言标准。如果您要分配的功能本身,你需要分配函数的名称是这样的:
$title = 'the_title'
,然后在您想要的功能,被称为地方,你只要写:
$title()
这将正常调用该功能。作为一个经验法则,你可以说如果()后面跟着一个东西,它将立即被调用。
你不分配功能,你调用该函数和指派返回值给你变量。 – aynber
那么我应该如何将它分配给这个变量,以便我可以在HEREDOC中调用它? – Andrew
http://php.net/manual/en/functions.variable-functions.php – litelite