php——13-include 和 require 文件引入
cc.php 文件
<?php
class name
{
public $s1 = 0;
public $s2 = 1;
public function __construct()
{
echo 'hello world!';
}
public function s1()
{
echo $this->s1;
}
public function s2()
{
echo $this->s2;
}
}
$name = new name();//hello world!
include 和 require
include
<?php
include ('cc.php');//hello world!
echo "<br>";
$name->s1();//0
$name->s2();//1
echo "<br>";
echo "我在 cc2.php 中引用了 cc.php 并调用了对象方法";
require
<?php
require ('cc.php');//hello world!
echo "<br>";
$name->s1();//0
$name->s2();//1
echo "<br>";
echo "我在 cc2.php 中引用了 cc.php 并调用了对象方法";
两者区别
include在文件引入出错,之后代码会继续运行
<?php
include ('error');//故意引入错误文件
echo "<br>";
echo "<h1 style='color: #0ab4f7'>hello world!</h1>""; //hello world!会继续显示
require在文件引入出错,之后代码会停止运行
<?php
require ('error');//故意引入错误文件
echo "<br>";
echo "<h1 style='color: #0ab4f7'>hello world!</h1>""; //hello world!不会显示
include_once 和 require_once
include_once
因为 include 重复引入会报错,如下:
<?php
include ('cc.php');
include ('cc.php');
include ('cc.php');//hello world!
echo "<br>";
$name->s1();
$name->s2();
echo "<br>";
echo "我在 cc2.php 中引用了 cc.php 并调用了对象方法";
所以引入了 include_once
<?php
include_once ('cc.php');
include_once ('cc.php');
include_once ('cc.php');//hello world!
echo "<br>";
$name->s1();//0
$name->s2();//1
echo "<br>";
echo "我在 cc2.php 中引用了 cc.php 并调用了对象方法";
require_once
原因同上,代码:
<?php
require_once ('cc.php');
require_once ('cc.php');
require_once ('cc.php');//hello world!
echo "<br>";
$name->s1();//0
$name->s2();//1
echo "<br>";
echo "我在 cc2.php 中引用了 cc.php 并调用了对象方法";