Skip to content
Advertisement

How to call variable inside function while using require or include outside that function in php

So, can we call a variable inside function using require or include without using it in the function?

This is the example code:

  1. Include / Require file (let’s say the file is “include.php”)
<?php
    $var1 = "Some Value";
    $var2 = "Another Value";
?>
  1. Index file
<?php
    require 'include.php';
    function test1(){
        echo $var1;
    }

    function test2(){
        echo $var2;
    }

    test1();
    test2();
?>

Expected output :

Some Value Another Value

Advertisement

Answer

The use of include/require is actually not relevant for your question. An include or a require will only “merge” the contents of other files to your code in order to become available.

As others have mentioned you need to use the global keyword. In many other programming languages the global variables are visible inside functions by default. But in PHP you need to explicitly define which variables that should be visible in each function.

Example:

<?php  
    $a = "first";
    $b = "second";
    $c = "third";

    function test() {
        global $a, $b;
        echo $a . " " . $b . " " . $c;
    }

    test();   // This will output only "first second" since variable $c is not declared as global/visible in the test-function
?>

However, if the variables should be treated as static constants I would recommend you to define them as constants. Constants have a “real” global scope and you do not need to use the global keyword.

<?php  
    define("A", "first"); 
    define("B", "second");
    define("C", "third");

    function test() {
        echo A . " " . B . " " . C;
    }

    test();   // This will output "first second third". You don't need to use the global keyword since you refer to global constants
?>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement