2016年2月14日 星期日

php Include file


PHP include and require Statements

It is possible to insert the content of one PHP file into another PHP file (before the server executes it), with the include or require statement.
The include and require statements are identical, except upon failure:
  • require will produce a fatal error (E_COMPILE_ERROR) and stop the script
  • include will only produce a warning (E_WARNING) and the script will continue

Syntax

include 'filename';

or

require 'filename';


Example 1

Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>

Example

<html>
<body>


<?php include 'footer.php';?>

</body>
</html>
執行的的結果如下:


Example 2

Assume we have a standard menu file called "menu.php":
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>

Example

<html>
<body>

<div class="menu">
<?php include 'menu.php';?>
</div>


</body>
</html>
執行結果如下:


Example 3

Assume we have a file called "vars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "vars.php" file, the variables can be used in the calling file:

Example

<html>
<body>

<h1>Welcome to my home page!</h1>
<?php include 'vars.php';
echo "I have a $color $car.";
?>

</body>
</html>

PHP include vs. require

The require statement is also used to include a file into the PHP code.
However, there is one big difference between include and require; when a file is included with the include statement and PHP cannot find it, the script will continue to execute:



Use require when the file is required by the application.

Use include when the file is not required and application should continue when file is not found.





沒有留言:

張貼留言