PHP在两个文件之间传递变量

时间:2013-10-07 15:00:21

标签: php variables include

我有一段代码:

foreach (glob('mov/$context.mov') as $filename){ 
    $theData = file_get_contents($filename) or die("Unable to retrieve file data");
}

这是在该glob中添加变量的正确方法吗? $上下文

另外,在我的新文件中,我想用$ context替换一个单词,所以我会写

$context = "word"; // so it adds that word to the glob function when the script is included in a different file.

3 个答案:

答案 0 :(得分:3)

PHP变量不在单引号内插值。使用双引号或将变量放在引号之外

foreach (glob("mov/$context.mov") as $filename){ 

foreach (glob('mov/'.$context.'.mov') as $filename){ 

如果你在foreach之前做$context = "word";那么glob会查找mov/word.mov

Reference

答案 1 :(得分:1)

您应该在glob函数的第一个参数中使用双引号。

glob("mov/$context.mov")

或者,如果您愿意,可以使用括号

glob("mov/{$context}.mov")

这样变量名将被替换为值。

修改
对于另一个问题: 具有glob函数的脚本可以多次执行,在包含脚本之前更改$context变量的值。 例如:

$context = "word";
include("test.php");

$context = "foo";
include("test.php");

答案 2 :(得分:1)

您可以使用以下任一方式 -

1。glob("mov/$context.mov")

2。glob("mov/".$context.".mov")

注意 与双引号语法不同,特殊字符的变量和转义序列在单引号字符串中不会展开。

供参考: Read More Here