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)?
include?includewill work as expected. But, let's just say I need that variable$array1in 100 different files. Is there no other way thanincludeing it in all 100 files? Becauseincludewill read and parse the file again.except storing $array1 in $GLOBALS variableyou can use a type of registry instance that holds global API data (not global variables)