包括我,包括像这样内部函数变量在PHP
// some function
function SomeFunction()
{
$someData = 'SomeData';
include_once('some_file.php');
}
// some_file.php
<?php echo $someData; ?>
我将如何得到这个工作,其中包括:文件可以使用变量从调用函数的另一个文件中的函数?我将使用一些输出缓冲。
包括我,包括像这样内部函数变量在PHP
// some function
function SomeFunction()
{
$someData = 'SomeData';
include_once('some_file.php');
}
// some_file.php
<?php echo $someData; ?>
我将如何得到这个工作,其中包括:文件可以使用变量从调用函数的另一个文件中的函数?我将使用一些输出缓冲。
只要$someData
在SomeFunction()
定义,some_file.php
将不得不$someData
访问。
如果您需要访问SomeFunction()
以外的变量,请将它们作为参数传递给SomeFunction()
。
这已经可用:)
最好是不要做使用全局变量所有,但传递变量参数:
function SomeFunction()
{
$someData = 'SomeData';
include_once('some_file.php');
some_foo($someData);
}
否则你可能会改变你的代码库中的代码spaghetty,至少在长远。
我真的不想这样做。我正在构建一个简单的视图引擎。 – 2009-12-02 17:34:34
你的意思是像smarty这样的模板系统,但更简单?如果是的话,我会为你提供合适的解决方案。 – Flavius 2009-12-02 19:02:50
似乎有点无组织的,包括函数文件...关于...
function SomeFunction()
{
$someData = 'SomeData';
return $someData;
}
$data = SomeFunction();
<?php include('file.php') ?> // file.php can now use $data
你不必做的任何事情。 include()
(和它的兄弟姐妹)的用法类似于在include()被调用的位置将包含文件的代码复制粘贴到包含文件中。
简单实例
test.php的
<?php
$foo = 'bar';
function test()
{
$bar = 'baz';
include 'test2.php';
}
test();
test2.php
<?php
echo '<pre>', print_r(get_defined_vars(), 1), '</pre>';
再次,这是类似于组合
<?php
$foo = 'bar';
function test()
{
$bar = 'baz';
echo '<pre>', print_r(get_defined_vars(), 1), '</pre>';
}
test();
它是否必须直接相关?我正在使用'_include_once',它扩展了输入'include_once'作为目录偏移量。 – 2009-12-02 17:37:01