繁体   English   中英

在PHP中,如何在评估字符串变量之前将其替换?

[英]In PHP, how do I substitute a string variable before it's evaluated?

在PHP尝试评估其真值之前,是否可以扩展/替换变量?

我正在尝试编写一个Wordpress模板,该模板将根据我们所在的页面执行不同的查询。 如果在主页上,查询应如下所示:

while ( $postlist->have_posts() ) : $postlist->the_post();
    // code...

如果我们不在主页上,则查询应如下所示:

while ( have_posts() ): the_post();
    // code...

所以我想我会尝试一下:

$query_prefix = ( is_front_page() ) ? '$postlist->' : '';

$query_condition = $query_prefix.'have_posts()';
$query_do        = $query_prefix.'the_post()';

while ( $query_condition ): $query_do;
    // code...

问题是,这正在创建一个无限循环,因为$query_condition是一个字符串,其计算结果为TRUE。 似乎PHP从未“读取”变量的内容。 我需要我的变量从字面上扩展自己,然后才提供其评估。 谁能告诉我该怎么做?

这些答案中的任何一个都可以,但是提供了另一种选择:

if(is_front_page()) {
    $callable_condition = array($postlist,'have_posts');
    $callable_do = array($postlist,'the_post');
} else {
    $callable_condition = 'have_posts';
    $callable_do = 'the_post';
}

while(call_user_func($callable_condition)) : call_user_func($callable_do);

另外,如果您在对象内部,则可以使用array($this,'method')调用对象的方法。

处理此问题的一种方法是在while条件中使用逻辑或语句根据is_front_page()的结果基于不同的对象进行循环,然后再使用if语句来控制对the_post()的调用。

// loop while the front page and $postlist OR not the front page and not $postlist
while ( (is_front_page() && $postlist->have_posts() ) || ( !is_front_page() && have_posts() ) ): 
    // use $postlist if on the front page
    if ( is_front_page() && !empty($postlist) ){
        $postlist->the_post(); 
    } else { 
        the_post();
    }
    // the rest of your code
endwhile;

也许这样的例子可能会帮助您。 这是关于使用变量的变量

class A {
    public function foo(){
        echo "foo" ;
    }
}

$a = new A() ;

$obj = 'a' ;
$method = "foo" ;


${$obj}->$method() ; //Will echo "foo"

我一直使用the_title来确定页面。

$isHomePage = false;
if(the_title( '', '', FALSE ) == "Home")
{
    $isHomePage = true;
}

然后,我将$ isHomePage用作其他我稍后在页面中需要的标志。 可以将其更改为查找您要选择的任何页面。 如果页面名称很长,它可能会变得很毛茸茸,所以就是这样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM