Search code examples
phpmysqlinclude

PHP - Accessing variables from different files


I have 3 files in my project. For arguments sake let's called them a.php, b.php and c.php.

In a.php I have a declared variable: $sql_connection

In b.php I have declared a function: check_if_logged_in()

With these declared, I now want to be able to use the variables across my files. I have included a.php in my b.php file, and I included my b.php inside c.php.

I'd expect this all to work but for some reason b.php isn't getting $sql_connection from a.php?

My a.php file:

<?php

    $sql_connection = mysqli_connect("localhost", "user", "password", "database");

?>

My b.php file:

<?php

    include ("a.php");

    function check_if_logged_in() {

        $sqlquery = mysqli_query($sql_connection, ...

    }

?>

My c.php file:

<?php

    include ("b.php");

    check_if_logged_in();

?>

Solution

  • The problem is you are trying to use the variable $sql_connection within a function, which is initialised/declared outside; i.e. you have a scope issue!

    Read up on it here: http://php.net/manual/en/language.variables.scope.php

    Solution;

    A. Pass $sql_connection to the function call like this: check_if_logged_in($sql_connection)

    or

    B. Use the global for e.g.

    function check_if_logged_in() {
        global $sql_connection;
        $sqlquery = mysqli_query($sql_connection, ...
    }
    

    P.S. Although option B works; it is not recommended as it is considered bad pratise; see Are global variables in PHP considered bad practice? If so, why?