Consider below scenario -
File : array.php
<?php
$array1 = array();
$array1['name'] = "Adam";
$array1['gender'] = "Male";
$array1['age'] = 34;
File : file1.php
<?php
function printArrayContent(){
require_once 'array.php';
var_dump($array1);
}
printArrayContent();
include_once "file2.php";
File : file2.php
<?php
require_once "array.php";
echo "File 2";
print_r($array1);
When I run file1.php I get below output -
OUTPUT
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
Why am I not able to access $array1
in file2
? What is the solution for this (except storing $array1
in $GLOBALS
variable)?
require_once includes ONCE a same file. Since your already have included it in your file1.php
, PHP engine does not include it another time in your file2.php
and so you don't have access to the variables in your file2.php scope.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.