首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确地从不同的文件调用函数?

如何正确地从不同的文件调用函数?
EN

Stack Overflow用户
提问于 2018-03-14 09:14:18
回答 1查看 25关注 0票数 2

所以我的主文件里有这个代码。

代码语言:javascript
复制
require_once(plugin_dir_path(__FILE__) . 'load_functions.php');

add_shortcode( 'ccss-show-recipes', 'ccss_show_tag_recipes' );
function ccss_show_tag_recipes() {

global $post;
global $wp;

$html = '';

$url = home_url( $wp->request );
$path = parse_url($url, PHP_URL_PATH);
$pathFragments = explode('/', $path);
$currentPage = end($pathFragments);
// $html.= '<p>'.$currentPage.'</p>';

    if ($currentPage == 'recipes') {

      ccss_load_all_recipes();


    } elseif ( in_array( $currentPage ,["cleanse","combine","commence","commit","complete","consolidate"] ) ) {

        //load_phases();

    } elseif ( in_array( $currentPage ,["basic-marinades","basic-stock-recipes"] ) ) {

       // load_recipe_type();

    }

    return $html;

   // Restore original post data.
   wp_reset_postdata();

}

我在这里有load_functions.php的功能

代码语言:javascript
复制
function ccss_load_all_recipes() {
 //code here that wont return

$html .= '<p>test</p>'; //--> It wont display this
echo 'test'; //---> This will be displayed
}

当我调用ccss_load_all_recipes()时,它不会返回任何东西,对我犯了什么错误有什么想法吗?但是,当我尝试回显语句时,它会返回它。

谢谢,卡尔

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-14 09:28:00

函数css_load_all_recipes()不知道变量$html。为了实现这一点,您应该将$html变量传递到函数中,并在结束时再次返回它。

代码语言:javascript
复制
// in your main file
$html = ccss_load_all_recipes($html);

// in load_functions.php
function ccss_load_all_recipes($html = '') {
    $html .= '<p>test</p>';
    return $html;
}

编辑:其他可能性包括:将$html声明为全局变量,或者将$html作为引用传递,这样您就不必将修改后的html返回主文件。但是,我建议不要使用这两个选项,除非您在应用程序中多次遇到相同的问题。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49273648

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档