camursm
camursm

Reputation: 193

PHP: Including files dependent on each other

Two files are dependent on each other:

FILE1:

$var1 = 'Straw ' . $var2;

FILE2:

$var2 = ' berry';
$var3 = $var1;

FILE3:

// this file should include FILE1 and FILE2

How should one go about including FILE1 and FILE2 in FILE3 in a way that makes sure the three variables are properly populated?

Thank you.

Upvotes: 1

Views: 376

Answers (3)

camursm
camursm

Reputation: 193

Many thanks everyone for your input.

One can do as @texelate and @Oke Tega suggests and put the variables in the right order, then distribute them into different files.

But as @Magnus Eriksson pointed out, this is circular dependency and bad design, it simply cannot be done.

Upvotes: 0

Oke Tega
Oke Tega

Reputation: 883

Since FILE 1 contains variable used in FILE 2, FILE 1 should be included first in FILE 3. So FILE 3 would be something like

include ("file1.php");
include ("file2.php");

But since the variables are dependent on each other, why not have them in the same file unless you have a reason some how.

NOTE: var2 would be undefined in FILE 1. So my advice is to put both variables that are dependent on each other in one FILE. So FILE 1 an be something like

$var2 = ' berry';
$var1 = 'Straw ' . $var2;

Then FILE 2

$var3 = $var1;

Then you include as above.

Upvotes: 0

texelate
texelate

Reputation: 2498

You actually will get a warning about an undefined variable regardless of the order you include them due to your design — since file 1 requires $var2 and file 2 requires $var1.

Instead do something like this:

$var2 = 'berry';
$var1 = 'Straw ' . $var2;
$var3 = $var1;

You can split these up in to separate files so long as they are called in the above order.

Upvotes: 1

Related Questions