douzhao2047
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
    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.

    点赞 评论
  • dongyan1993
    dongyan1993 2013-12-07 13:16

    If you leave $class empty in your layout_class($class) then your function is invalid anyways. You need to declare something for the variable layout_class($class = null) or if you call it layout_class(null) but if you do not declare it, it will not work as the way you have it set up is required.

    The rest of your code is okay.

    Also, you have declared $class in your function, and you are using it as a variable within the function, I would rename your output ie

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

相关推荐