1

如果我有三个文件“ index.php”“ file.php”和“ fns.php

第一个例子(有效):

索引.php:

<?php
  $var = "Variable Data";
  include "file.php";
?>

文件.php:

<?php
  var_dump($var);  #Output will be : string(13) "Variable Data"
?>

第二个例子(它不起作用):

索引.php:

<?php
  include "fns.php";
  $var = "Variable Data";
  load("file.php");
?>

fns.php:

<?php
  function load($file) { include $file; }
?>

文件.php

<?php
  var_dump($var); #Output will be : NULL
?>

如何使用类似函数包含文件load()并保持变量在没有额外的情况下工作Global $var;

我的解决方案:

<?php
  function load($file)
  {
    $argc = func_num_args();
    if($argc>1) for($i=1;$i<$argc;$i++) global ${func_get_arg($i)};

    include $file;
  } 

  #Call :
  load("file.php", "var");
?>
4

2 回答 2

5

因为您将文件包含在函数内部,所以包含文件的范围就是该函数的范围。

为了包含其他变量,请将它们注入函数中。

function load($file, $var) { include $file; }

这样,$var将可用。


你甚至可以让事情变得更有活力:

function load($file, $args) { extract($args); include($file); }

并像这样使用它:

load("path/to/file.php", array("var"=>$var, "otherVar"=>$otherVar));

PHP 会将变量提取为正确的符号名称 ( $var, $otherVar)。

于 2012-06-07T08:31:14.713 回答
1

当您尝试在函数中包含文件时,变量的范围在函数中。如果您在函数加载中设置变量,那么它不是NULL.

function load($file, $var) {
    include($file);
}
于 2012-06-07T08:34:53.517 回答