John Davidson

string - Is there a way to use a variable from another file in a php include?

0 comments
Message:


So basically I have a file, lets say file1.php and it includes another file2.php.



file1.php contains a variable called $dateString that I have performed some operations on.



file2.php also has the same variable called $dateString however this variable is not being referenced within this include file even though $dateString was initialized prior to including file2.php.



So this is currently how file1.php looks like:



$dateString = 'some expression';

include 'file2.php';


file2.php is basically trying to echo out the variable that was initialized in file1.php



echo $dateString;


Everything else from file2.php is being called properly except that one variable.



Hopefully this makes sense. Is this possible in PHP? I have read in other places that you need to make the variables global and others have mentioned how you cant reference a variable from a parent file within a child file..any thoughts? Thanks in advance!



My Answer:
Yes, it is possible to use a variable from another file in a PHP include. One way to do this is by using the global keyword to make the variable accessible in the included file.

In file1.php, you can declare the variable as global before including file2.php like this:

php
$dateString = 'some expression';
global $dateString;
include 'file2.php';


And in file2.php, you can access the variable using the global keyword as well:

php
global $dateString;
echo $dateString;


This should allow you to use the $dateString variable from file1.php in file2.php.

Rate this post

3 of 5 based on 9768 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us