Search code examples
phpscopeincluderequire

Undefined variable error although the variable IS present in an already included file


I have a PHP script named constants.php

constants.php:-

<?php
$projectRoot = "path/to/project/folder";
...
?>

And then I have another file named lib.php

lib.php:-

<?php
class Utils {
  function doSomething() {
    ...
    // Here we do some processing where we need the $projectRoot variable.
    $a = $projectRoot; //////HERE, I GET THE ERROR MENTIONED BELOW.
    ...
  }
}
?>

And then I have another file named index.php, which includes both of the above files.

index.php:-

<?php
...
require_once "constants.php";

...

require_once "lib.php";
(new Utils())->doSomething();
...
?>

Now, the problem is that when I run index.php, I get the following Error:

Notice: Undefined variable: projectRootPath in /var/www/html/test/lib.php on line 19

My question is that why am I getting this error and how can I resolve it?

Apparently, it is related to scope, but I have read the include and require simple copy and paste the included code into the script where it is included. So I am confused.


Solution

  • Because, you are accessing variable in function scope.

    Variables outside function are not accessible inside function.

    You need to either pass them as arguments or you need to add keyword global to access it.

    function doSomething() {
     global $projectRoot;
        ...
        // Here we do some processing where we need the $projectRoot variable.
        $a = $projectRoot; 
    

    As per @RiggsFolly:

    Pass as a parameter

    require_once "lib.php";
    (new Utils())->doSomething($projectRoot);
    

    ...

    <?php
    class Utils {
      function doSomething($projectRoot) {
        ...
        // Here we do some processing where we need the $projectRoot variable.
        $a = $projectRoot; //////HERE, I GET THE ERROR MENTIONED BELOW.
        ...
      }
    }
    ?>