Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

there is nothing magically happening when you use PHP's include(). the included file's code is basically just inserted at the point where you are including it - resulting in one bigger PHP file.
it doesn't really matter if the "parent" or in the "child" file - it's the position that matters since PHP will parse the single resulting file from top to bottom.

for example: if you set the variable in file A before including file B, file B will know about the variable. but if you set the variable in file A after including file B - file B doesn't know it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...