在函数内部使用include时,如何访问include之前声明的变量?

时间:2017-01-11 16:26:36

标签: php class oop include

好吧,我把代码搞砸了很多...... 我不确定我想要完成的是否可能。

我有一个名为Example的类,其名为Template的函数有1个参数

Class Example{
    public function Template($root){
        include ROOT."/templates/{$root}.php";
    }
}

我有一系列产品,我实例化该类并运行模板函数

$products = array("garbage");
$test = new Example;
$test->Template("product");

以下是/templates/product.php

的示例副本
print 'Test';
print_r($products);

我找回显示“Test”的页面但我无法访问在Template函数之前定义的$products数组。

如果我走直接include ROOT."/templates/product.php";路线,一切正常。

我无法在函数中使用include吗?

2 个答案:

答案 0 :(得分:3)

如果您要去globals,那么其他答案似乎总是使用$products。这是一种动态的方式,因此您可以通过'user'$users(添加了' s')等等...

Class Example{
    public function Template($root){
        ${$root.'s'} = $GLOBALS["{$root}s"];
        include ROOT."/templates/{$root}.php";
    }
}

但是,最好在函数中传递变量并使用标准名称,$data在这种情况下,所有模板都使用$data

Class Example{
    public function Template($root, $data){
        include ROOT."/templates/{$root}.php";
    }
}

$products = array("garbage");
$test = new Example;
$test->Template("product", $products);

如果您因任何原因确实需要$products等特定名称,请考虑将其作为关联数组传递:

Class Example{
    public function Template($root, $data){
        extract($data);
        include ROOT."/templates/{$root}.php";
    }
}

$products = array("garbage");
$test = new Example;
$test->Template("product", compact("products");

答案 1 :(得分:1)

您的问题是您的变量$ product是在全局范围内定义的,并且您在函数内包含一个文件,因此,该文件将引用该函数的本地范围内的$ product变量。

试试这个:

    Class Example{
        public function Template($root){
            global $products;
            include ROOT."/templates/{$root}.php";
        }
    }