search
Homephp教程php手册PHP入门基础之引用文件学习笔记

引用文件在php中与asp中引用文件有一定区别,下面我来介绍在php中利用require 与include引用文件实例吧。

引用文件是PHP在一大特特色之一,这个方法可以将常用的功能与函数放在一个文件之中,而其他页面需要用到这些功能或函数时,就直接通过引用这个文件来调用这些函数了,如果不引用的话,重新在那个页面上写上相同的函数会大大的加重开发者的工作量,也加大了程序的代码量,不利于后期的维护以及二次开发。

PHP引用文件的方法有两个,分别利用到的函数是 require() 和 include(),两种引用的效果是一样的,但这两个函数有不同之处:如果 require 引用文件时不反回任何值,出错就致命的错误,程序将终止继续执行;使用该函数进行引用时,你要确保代码都是正确的情况下使用,而当 include 引用文件时有反回值,出错时它仍继续执行后面代码,所以建议大家尽量使用第一个函数 require 来引用文件,它没有值反回,速度和效率上相对比 include 要快,而通常 require 会放在PHP程序的最前面,PHP 程序在执行前,就会先读入 require 所指定引入的文件,使它变成 PHP 程序网页的一部份,常用的函数,亦可以这个方法将它引入网页中。

实例代码如下:

<?php  
    require(&#39;sql.php&#39;); // 该函数通常放在开头,例如:引用SQL数据库连接函数的文件  
    echo &#39;引用文件示范&#39;;  
    include(&#39;hello-world.php&#39;); // 该函数一般是放在流程控制的处理部分中  
?>

这时有人可能就会问,当某个页面引用多个文件时,而这些被引用的文件也都引用了其它一个或多个相同的文件,有时侯没必要引用那么多次,那么怎样才让PHP只引用一次就行了呢?当然,PHP也有对应的方法的,就是在原函数的基础上加上个“后缀”一样的声明,就是把函数分别变为 require_once()和 include_once(),如下示例:

<?php  
    require_once(&#39;sql.php&#39;); // 声明只引用sql.php文件一次  
    echo &#39;引用文件示范&#39;;  
    include_once(&#39;hello-world.php&#39;); //声明只引用hello-world.php文件一次  
?>

               
               

本文地址:

转载随意,但请附上文章地址:-)

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment