Php 如何将两个函数包装到一个调用中
好的,我正在做一个Wordpress项目(PHP),使用高级自定义字段和一点PHP。我创建了两个函数,它们将围绕一些文本创建一个容器div:Php 如何将两个函数包装到一个调用中,php,wordpress,function,Php,Wordpress,Function,好的,我正在做一个Wordpress项目(PHP),使用高级自定义字段和一点PHP。我创建了两个函数,它们将围绕一些文本创建一个容器div: <section> <?php container_start(); ?> Text goes here <?php container_end(); ?> </section> 这里有文字 这将生成以下代码: <section> <div class="cont
<section>
<?php container_start(); ?>
Text goes here
<?php container_end(); ?>
</section>
这里有文字
这将生成以下代码:
<section>
<div class="container">
Text goes here
</div>
</section>
这里有文字
这是伟大的,因为它的工作预期。幕后的两个功能是:
function container_start() {
$container = get_sub_field('container');
if ($container):
echo '<div class="container">';
endif;
}
function container_end() {
$container = get_sub_field('container');
if ($container):
echo '</div>';
endif;
}
函数容器_start(){
$container=get_sub_字段(“container”);
如果($集装箱):
回声';
endif;
}
函数容器_end(){
$container=get_sub_字段(“container”);
如果($集装箱):
回声';
endif;
}
问题是:有没有一种方法可以优化这是如何实现的?我发现仅仅调用两个函数来添加并关闭一个div并不太实际。有没有一种方法可以将其封装为一个调用?您仍然需要使用两个函数,但也许您可以这样做:
function container_start() {
ob_start();
}
function container_end() {
$container = get_sub_field('container');
if ($container)
echo '<div class="container">';
echo ob_get_contents();
ob_end_clean();
if ($container)
echo '</div>';
}
函数容器_start(){
ob_start();
}
函数容器_end(){
$container=get_sub_字段(“container”);
如果($集装箱)
回声';
echo ob_get_contents();
ob_end_clean();
如果($集装箱)
回声';
}
那么这会有什么作用:
当您调用container_start时,ob_start对php说要保留打印的所有内容
然后,当您调用container_end时,您执行container操作,然后调用ob_get_contents,返回php保留的所有内容(并对其进行回显)和ob_end_clean,这表示php停止保留打印的所有内容
这样,您仍然有两个函数,但是get_sub_字段('container')只会被调用一次当前设置的优点是标记是平衡的:有一个开始的“标记”和一个匹配的结束的“标记”。虽然这确实需要您管理标记的平衡,但我认为这比其他方法更干净,并且符合您在HTML中的操作方式。在此基础上添加的任何附加魔法(比如跟踪一些标记堆栈并具有通用的
end()
函数)都会增加复杂性,并可能影响可读性。WordPress没有在PHP上使用模板语言,因此您不会比已经拥有的更好
也就是说,消除结束标记的一个选项是将多行字符串传递给函数。我对这个方法不是很在行,但它是可用的,可能是其他方法的起点
<?php
$var = 'foo';
function wrapper_function($inner) {
echo '<div class="container">';
echo $inner;
echo '</div>';
}
?>
Something before.
<?php wrapper_function(<<<EOF
This text goes inside. I can put <html> in here, plus
any $var since I'm using HEREDOC rather than NOWDOC.
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
EOF
); ?>
Something after.
以前的事。
Something before.
<div class="container"> This text goes inside. I can put <html> in here, plus
any foo since I'm using HEREDOC rather than NOWDOC.
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc</div>
Something after.