douzhao2047 2013-12-07 13:12
浏览 6
已采纳

PHP:如何在另一个函数中检查函数的返回值

I have a function which returns a value that I'd like to check via another one. I can not echo it in the first function as far as I know, as it's used in a wordpress filter for body_class and outputted there.

So, how do I check what the returned value is in another function?

An example of the first function that returns $class, which is what I want to check:

function layout_class( $class ) {
    // There is lots of more functionality here for the $layout variable
    $layout = 'col-3cm';

    $class[] = $layout;
    return $class;
}
add_filter( 'body_class', 'layout_class' );

Now, this class decides whether or not to load a secondary sidebar template. So I would like to do:

function sidebar_dual() {
    $layout = layout_class();   
    if (
        ( $layout == 'col-3cm' ) ||
        ( $layout == 'col-3cl' ) ||
        ( $layout == 'col-3cr' )
    )
    { get_template_part('sidebar-2'); }
}

Since I can't echo out the first function, and don't want to write another function as it is quite big - how do I approach it? Is there an easy way to check a return value, similar to echo?

  • 写回答

2条回答 默认 最新

  • dongshi4589 2013-12-07 13:21
    关注

    It looks like you need to refactor your code.

    You just need to move the code that determines the layout into a separate function that you can call both inside the filter and inside the sidebar_dual() function:

    function get_layout_mode(){
    
       // There is lots of more functionality here for the $layout variable
       $layout = 'col-3cm';
    
       return $layout;
    }
    

    The filter function becomes:

    function layout_class( $class ) {
        $class[] = get_layout_mode();
        return $class;
    }
    add_filter( 'body_class', 'layout_class' );
    

    And in your sidebar_dual() function call get_layout_mode() instead of layout_class()


    It is possible to work with your current code too, by splitting the string returned by WP's get_body_class() function into an array then checking if any of those 3 classes are present inside the array. I would go with the first option though, because it's clearer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型