Jump to content


How to use variables from other included files


3 replies to this topic

#1 George

    Newbie

  • Members
  • Pip
  • 2 posts

Posted 26 August 2010 - 11:01 AM

Hy!
I have 3 files:

file 1 (index.php) includes 2 files: file2.php and file3.php

In file2.php I create $aditionalStuff and in file3.php I want to use $aditionalStuff, but it wont work (like it wasn't initialized).

How can I make this work?

Thanks!

#2 Gustavo el Geranie

    Advanced Member

  • Members
  • PipPipPip
  • 716 posts

Posted 26 August 2010 - 11:39 AM

That should work. Try require instead of include, and set error_reporting(E_ALL) to get all error messages.
Those people who think they know everything are a great annoyance to those of us who do - Isaac Asimov

#3 George

    Newbie

  • Members
  • Pip
  • 2 posts

Posted 26 August 2010 - 01:00 PM

View PostGustavo el Geranie, on 26 August 2010 - 11:39 AM, said:

That should work. Try require instead of include, and set error_reporting(E_ALL) to get all error messages.

Well, it doesn't. I have error reporting but there are no errors.

I don't know if you understood me, file3 doesn't include file2, file 1 includes 2 and 3.
File 2 and 3 are individual files that are included in file 1.
I have no idea how to explain in other way :)

#4 Shoel

    Administrator

  • Administrators
  • 125 posts

Posted 27 August 2010 - 06:05 PM

Hi George,

The way I understand this, is that you have the following structure:

   -------includes--> File2
   |
File1
   |
   -------includes--> File3
If File2 declares a variable that you would like to use in File3 - the order of which you include them is of importance. File2 will have to be included before File3. So that in index.php (aka File1) - you have something like this:

<?php
require_once('file2.php');
require_once('file3.php');
?>
You will also have to consider the variable scope here. If your file2.php contains the following:

<?php
$aditionalStuff = 'some string';
?>
And file3.php includes the follwing:

<?php
function printAdditionalStuff(){
  print $aditionalStuff;
}
?>
You would not get any output because $aditionalStuff in file2.php exists in the global space - while the print in printAdditionalStuff() uses a reference to a variable in the local scope within that function. The solution to this is to either pass the value in as a parameter when you call the function, or use the global keyword to create a reference to the variable in the global namespace:

<?php
function printAdditionalStuff(){
  
  global $aditionalStuff;

  print $aditionalStuff;
}
?>
Hopefully that makes some sense to you - otherwise feel free to ask and I will try to explain it better. :)

- S.
Hi there! If you found this post useful, or used this information to help others, we would greatly appreciate a link back to our forum from your website/blog. Thanks! =)





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users