包含文件中的NULL变量

Joh*_*ohn 1 php global-variables

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

第一个例子(它的工作原理):

index.php:

<?php
  $var = "Variable Data";
  include "file.php";
?>
Run Code Online (Sandbox Code Playgroud)

file.php:

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

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

index.php:

<?php
  include "fns.php";
  $var = "Variable Data";
  load("file.php");
?>
Run Code Online (Sandbox Code Playgroud)

fns.php:

<?php
  function load($file) { include $file; }
?>
Run Code Online (Sandbox Code Playgroud)

file.php

<?php
  var_dump($var); #Output will be : NULL
?>
Run Code Online (Sandbox Code Playgroud)

如何使用类似函数包含文件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");
?>
Run Code Online (Sandbox Code Playgroud)

Mad*_*iha 5

因为您在函数内部包含了文件,所以包含文件的作用域是该函数的作用域.

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

function load($file, $var) { include $file; }
Run Code Online (Sandbox Code Playgroud)

这样,$var就可以了.


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

function load($file, $args) { extract($args); include($file); }
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

load("path/to/file.php", array("var"=>$var, "otherVar"=>$otherVar));
Run Code Online (Sandbox Code Playgroud)

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