将变量传递给方法中的包含文件

时间:2014-11-23 01:56:25

标签: php

我找不到这个问题的答案。我有一个用PHP编写的类。 PHP类方法中包含的文件似乎不是方法范围内的继承变量。

class Classname {
    public function template_editor (){
        $GLOBALS['template_editor'] = true; 
        $editable=false;
        $GLOBALS['editing'] = false;
        $template_html =  $this->thetemplate (array('editable'=>$editable));
        include (TEMPLATE_DIR_URI."/inc/template_editor.php");
    }
}

我希望将变量$ template_html传递给包含的文件,以便我可以回显它。我编写了很多函数,函数中声明的所有变量都传递给包含的文件,但它在类方法中不起作用。

在我目前的附带文件中;

<?php echo  $template_html;  ?>

...还有一些html和Jquery。我希望所有方法变量都可以在包含的文件中使用,以便我可以在包含的文件中使用它们。

1 个答案:

答案 0 :(得分:0)

来自documentation of include()

  

如果include发生在调用文件中的函数内,那么   调用文件中包含的所有代码都将表现得像它一样   已在该功能内定义。所以,它将遵循变量   该职能的范围。此规则的一个例外是魔术常量   在包含发生之前由解析器评估。

您的问题很可能就是这一行没有为$template_html

分配值
$template_html =  $this->thetemplate (array('editable'=>$editable));

或者您在template_editor.php中错误地引用了该变量。

如此检查$template_html的值可能会让您深入了解原因:

class Classname {
    public function template_editor (){
        $GLOBALS['template_editor'] = true; 
        $editable=false;
        $GLOBALS['editing'] = false;
        $template_html =  $this->thetemplate (array('editable'=>$editable));

        // Add this for debugging
        if (is_empty($template_html)) {
            error_log('$template_html is empty.');
        }

        include (TEMPLATE_DIR_URI."/inc/template_editor.php");
    }
}
相关问题