PHP require_once变量范围

时间:2017-03-07 13:34:08

标签: php

考虑以下情况 -

文件:array.php

<?php
    $array1 = array();
    $array1['name'] = "Adam";
    $array1['gender'] = "Male";
    $array1['age'] = 34;

文件:file1.php

<?php 
    function printArrayContent(){
        require_once 'array.php';
        var_dump($array1);
    }
printArrayContent();

include_once "file2.php";

文件:file2.php

<?php 
    require_once "array.php";
    echo "File 2";
    print_r($array1);

当我运行file1.php时,我得到以下输出 -

输出

array(3) {
 'name' =>
 string(4) "Adam"
 'gender' =>
 string(4) "Male"
 'age' =>
 int(34)
}
File 2PHP Notice:  Undefined variable: array1 in /private/tmp/file2.php on line 4
PHP Stack trace:
PHP   1. {main}() /private/tmp/file1.php:0
PHP   2. include_once() /private/tmp/file1.php:11

Notice: Undefined variable: array1 in /private/tmp/file2.php on line 4

Call Stack:
 0.0212     230512   1. {main}() /private/tmp/file1.php:0
 0.0226     232424   2. include_once('/private/tmp/file2.php') /private/tmp/file1.php:11

为什么我无法访问$array1中的file2?解决方法是什么(除了在$array1变量中存储$GLOBALS)?

1 个答案:

答案 0 :(得分:0)

require_once包含 ONCE 相同的文件。由于您已经将它包含在file1.php中,因此PHP引擎不再在file2.php中包含它,因此您无法访问file2.php范围内的变量。< / p>