I have 2 includes on a page. Let’s say they’re the header and footer:
<?php
include('header.php');
include('footer.php');
I need to use a variable from the footer in the header. Is this possible?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Unless there’s a reason you can’t, the simple solution is to set the variable used in inc2 in inc1 instead.
When a script is included outside of any function, the script executes in global scope, so anything it sets or defines that is scoped will have global scope. If a script is included within a local scope (such as in a function), the script executes in the same scope, so anything it defines is local. Note the included script can access variables local to a function.
However, global variables can be problematic. A better approach is to break down tasks into separate modules. Most modules are library scripts: they only define things (functions, classes) and don’t execute anything directly. The entry point (the top level script) doesn’t define anything; instead, it serves to connect everything and as a starting-off point for computation. Here’s a simple example with a database connection:
While technically
$dbis a global variable (note that this is merely sample code, rather than production code), it’s not to be accessed anywhere outside this script. Instead, it’s passed around according to the rules of capabilities (which was designed for security purposes, but the rules are actually just good OOP principles).