-1

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.

Shy
  • 542
  • 8
  • 20

1 Answers1

1

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.
    ...
  }
}
?>
Pupil
  • 23,834
  • 6
  • 44
  • 66
  • OUCH! Global?? Would be better to pass the value on the function call everytime – RiggsFolly Apr 03 '19 at 10:37
  • @RiggsFolly Why is that better? – Shy Apr 03 '19 at 11:32
  • 1
    Because you are never completely sure what a global will contain at any one point in time. By vertue of it being accessible from anywhere, anything may have changed its value meaning it wont be what you expect it to be when you get into the function – RiggsFolly Apr 03 '19 at 11:48