0

I trying to have a PHP script calling several functions that should do some operations on couple of variables.

Like for example have one function fetch the matrix, then the second is doing one operation over it, then the third doing different operation on it.

It all worked well when it was in one file, but now that I've split it up it won't work. I get all undefined index and undefined variable error.

What do I have to do with variables so that they should keep their values throughout the script?

Cornelius
  • 341
  • 5
  • 18

2 Answers2

0

The easiest way (and bad way in larger PHP projects, as this can make things very messy very fast), is to either use $GLOBALS['myvar'] to set/get the variable value for $myvar in a global scope. Or you can use:

<?php
global $myvar;
//use the $myvar below...

Use that anywhere, including inside a function, or in a new file, to use $myvar in a global scope.

On a side note, there are better ways to make something accessible "everywhere" depending on context. It may be a little outside the scope of this global question, but just be aware there are other ways, for instance using the Singleton method (enforce single instance of a class used throughout the software, retrieved with a static class that returns the object, like MyClass::getInstance()). For a simple 2/3 file script this probably doesn't matter as much (unless you need re-usable code), but for anything more complex, avoid using globals for everything. You will save a lot of headache, the code will be easier to maintain, and your peers won't snicker at you behind your back for using globals.

jonyo
  • 41
  • 3
0

Did you used require_once('file2.php') , and the same for the third file? Assuming you are running the first file.

Splitting fuctionallity into separate files requires those files to be included as if it was all in one file. Make sure that you did that.

Fadey
  • 430
  • 2
  • 11