2

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)?

4
  • 2
    how about just say : include? Commented Mar 7, 2017 at 13:41
  • 1
    include will work as expected. But, let's just say I need that variable $array1 in 100 different files. Is there no other way than includeing it in all 100 files? Because include will read and parse the file again. Commented Mar 7, 2017 at 13:42
  • You can code OOP and go for autoloading OR you can use php.ini auto.prepend to include a file always OR you have to include it in all 100 files. Commented Mar 7, 2017 at 13:44
  • except storing $array1 in $GLOBALS variable you can use a type of registry instance that holds global API data (not global variables) Commented Mar 7, 2017 at 13:47

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.