<%@include %>;指命将会在JSP编译时插入一个包含文本或代码的档案,当你使用<%@ include %>;指命时,这个包含的过程就当是静态的。静态的包含就是指这个被包含的档案将会被插入到JSP档案中去,这个包含的档案可以是JSP档案,HTML档案,文本档案。如果包含的是JSP档案,这个包含的JSP的档案中代码将会被执行。
如果你仅仅只是用include 来包含一个静态档案。那幺这个包含的档案所执行的结果将会插入到JSP档案中放<% @ include %>;的地方。一旦包含档案被执行,那幺主JSP档案的过程将会被恢复,继续执行下一行.
当一个档案被包含时,其中所包含的代码继承了 include 所在行的变数範围。从该处开始,调用档案在该行处可用的任何变数在被调用的档案中也都可用。不过所有在包含档案中定义的函式和类都具有全局作用域。
例子 16-5. 基本的include()例子
vars.php<?php$color = 'green';$fruit = 'apple';?>test.php<?phpecho "A $color $fruit"; // Ainclude 'vars.php';echo "A $color $fruit"; // A green apple?> 如果 include 出现于调用档案中的一个函数里,则被调用的档案中所包含的所有代码将表现得如同它们是在该函式内部定义的一样。所以它将遵循该函式的变数範围。
例子 16-6. 函式中的包含
<?phpfunction foo(){ global $color; include 'vars.php'; echo "A $color $fruit";}/ vars.php is in the scope of foo() so $fruit is NOT available outside of this scope. $color is because we declared it as global. /foo(); // A green appleecho "A $color $fruit"; // A green?>例子 16-7. 通过 HTTP 进行的include()
<?php/ This example assumes that is configured to parse .php files and not .txt files. Also, 'Works' here means that the variables $foo and $bar are available within the included file. /// Won't work; file.txt wasn't handled by as phpinclude '/file.txt?foo=1&bar=2';// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the// local filesystem.include 'file.php?foo=1&bar=2';// Works.include '/file.php?foo=1&bar=2';$foo = 1;$bar = 2;include 'file.txt'; // Works.include 'file.php'; // Works.?>相关信息参见使用远程档案,fopen()和file()。
<?php// This is WRONG and will not work as desired.if ($condition) include $file;else include $other;// This is CORRECT.if ($condition) { include $file;} else { include $other;}?>处理返回值可以在被包括的档案中使用return()语句来终止该档案中程式的执行并返回调用它的脚本。同样也可以从被包含的档案中返回值。可以像普通函式一样获得 include 调用的返回值。不过这在包含远程档案时却不行,除非远程档案的输出具有合法的 php 开始和结束标记(如同任何本地档案一样)。可以在标记内定义所需的变数,该变数在档案被包含的位置之后就可用了。