56
|
Chapter 2: Language Basics
ignore subsequent attempts to load the same file. For example, many page elements,
each stored in separate files, need to know the current user’s preferences. The element
libraries should load the user preferences library with
require_once
. The page designer
can then include a page element without worrying about whether the user preference
code has already been loaded.
Code in an included file is imported at the scope that is in effect where the
include
statement is found, so the included code can see and alter your code’s variables. This
can be useful—for instance, a user-tracking library might store the current user’s
name in the global
$user
variable:
// main page
include 'userprefs.inc';
echo "Hello, $user.";
The ability of libraries to see and change your variables can also be a problem. You
have to know every global variable used by a library to ensure that you don’t acci-
dentally try to use one of them for your own purposes, thereby overwriting the
library’s value and disrupting how it works.
If the
include
or
require
construct is in a function, the variables in the included file
become function-scope variables for that function.
Because
include
and
require
are keywords, not real statements, you must always
enclose them in curly braces in conditional and loop statements:
for ($i=0; $i < 10; $i++) {
include "repeated_element.html";
}
Use the
get_included_files( )
function to learn which files your script has included
or required. It returns an array containing the full system path filenames of each
included or required file. Files that did not parse are not included in this array.
Embedding PHP in Web Pages
Although it is possible to write and run standalone PHP programs, most PHP code is
embedded in HTML or XML files. This is, after all, why it was created in the first
place. Processing such documents involves replacing each chunk of PHP source code
with the output it produces when executed.
Because a single file contains PHP and non-PHP source code, we need a way to iden-
tify the regions of PHP code to be executed. PHP provides four different ways to do
this.
As you’ll see, the first, and preferred, method looks like XML. The second method
looks like SGML. The third method is based on ASP tags. The fourth method uses
the standard HTML
Do'stlaringiz bilan baham: |