Home Backend Development PHP Tutorial PHP中你应该知道的require()文件包含的正确用法_PHP

PHP中你应该知道的require()文件包含的正确用法_PHP

May 30, 2016 am 08:45 AM
require File contains

以前看一些PHP框架源码的时候,很奇怪在文件包含的时候,会用dirname(__FILE__)来拼凑文件路径,不知道这样做有什么好处,后来终于发现了其中的缘由。

我们来看一个简单的例子:

有a,b,c三个php文件。a.php在网站根目录,b.php在b文件夹下——b/b.php,c.php在c文件夹下——c/c.php。有些混乱?看图就一目了然了:

a.php 和 b.php 都包含了 c.php,最后 c.php 包含了d文件夹下的一个php文件——d/d.php。

我们先来看a.php:

<?php 
  $file_name = 'a.php';
  echo "this is a.php";
  echo "<hr>";
  require('c/c.php');
 ?>
Copy after login

很简单的代码,打印输出后,包含了c/c.php,接着,我们需要看c/c.php:

<?php 
  $c_file_name = 'c.php';
  echo 'this is c.php, is required by ' . $file_name;
  echo "<hr>";
  require('../d/d.php');
 ?>
Copy after login

打印输出 "this is c.php, is required by a.php",$file_name是在a.php中定义的变量。在最后,包含了d.php。因为d文件夹在当前c.php文件的上一层,所以,按照常理,我们会理所当然的把路径写成 "../d/d.php"。但是很遗憾,会报错。原因在于,在被包含的文件中如c.php,再去包含其他文件,路径是相对于最外层的父文件来说的,也就是相对于a.php,可以理解为因为你被我包含了,所以你要以我为准。看起来很玄乎,原理其实很简单:你可以把 require('c/c.php'); 看成是c/c.php文件里的代码,这样我们的a.php看起来可以是这个样子:

<?php 
  $file_name = 'a.php';
  echo "this is a.php";
  echo "<hr>";
  // require('c/c.php');
  $c_file_name = 'c.php';
  echo 'this is c.php, is required by ' . $file_name;
  echo "<hr>";
  require('../d/d.php');
 ?>
Copy after login

到此,你可以看到,我们要包含d/d.php文件时,刚才的路径是不是错误的了?因为,现在是在a.php的代码里,我们是相对于a.php文件来说的,当然,路径应该是 require('d/d.php'); 才对了。我们修改代码如下:

<?php 
  $file_name = 'a.php';

  echo "this is a.php";
  echo "<hr>";

  // require('c/c.php');
  $c_file_name = 'c.php';

  echo 'this is c.php, is required by ' . $file_name;
  echo "<hr>";

  require('d/d.php');
 ?>
Copy after login

此时,你还没有领悟到深意,需要往下看,我们再看b/b.php:

<?php 
  $file_name = 'b.php';
  echo "this is b.php";
  echo "<hr>";
  
  require('../c/c.php');
 ?>
Copy after login

不需要解释了吧,没啥问题,但是当你把 require('../c/c.php'); 换成 c/c.php 里面的代码的时候,你就会发现问题了,注意,我们刚才修改了c/c.php里的代码,把 require('../d/d.php'); 改成了 require('d/d.php'); 看下面包含进来后的代码:

<?php 
  $file_name = 'b.php';
  echo "this is b.php";
  echo "<hr>";
  
  // require('../c/c.php');
  $c_file_name = 'c.php';
  echo 'this is c.php, is required by ' . $file_name;
  echo "<hr>";
  require('d/d.php');
 ?>
Copy after login

那么,相对于 b/b.php 来说,require('d/d.php'); 的路径错了,应该是 require('../d/d.php'); 才对。你回去修改 c/c.php 中的require路径,但是不对呀,你改了之后,b/b.php可以正常运行了,但是 a/a.php 又不行了,是不是,它们共用 c/c.php ,牵一发动全身,怎么办呢。

这个时候,我们回到文章开头提到的 dirname(__FILE__),这可是个好东西,可以完全解决以上问题。用了它,就可以不用关心包含你的文件是哪个文件、在哪个路径下面了,不需要顾虑父文件所在的层级,因为,dirname(__FILE__)可以相对于当前文件指定路径。也就是说,我们需要将我们的 c/c.php 中的 require 路径换为:

<?php 
  $c_file_name = 'c.php';

  echo 'this is c.php, is required by ' . $file_name;
  echo "<hr>";

  require(dirname(__FILE__) . '/../d/d.php');
 ?>
Copy after login

这里,我们只需要把 c/c.php 作为参照,相对于它来说,d/d.php 在上一层。这样,就只有一个标准了,那就是,以我为准,管你包含我,还是他包含我,我只以我自己为准,我要包含的文件只相对于我自己而言了。

对于 dirname(__FILE__) 不明白的同修,请google,很简单。

好了,PHP技术分享到此结束,有任何疑问或有错误之处,请留言。话说,这是我的第一个标准技术博文。第一篇是水文,第二篇是准技术,今天终于写了篇技术的,欧也。

Statement of this Website
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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

vue3+vite: How to solve the error when using require to dynamically import images in src vue3+vite: How to solve the error when using require to dynamically import images in src May 21, 2023 pm 03:16 PM

vue3+vite:src uses require to dynamically import images and error reports and solutions. vue3+vite dynamically imports multiple images. If vue3 is using typescript development, require will introduce image errors. requireisnotdefined cannot be used like vue2 such as imgUrl:require(' .../assets/test.png') is imported because typescript does not support require, so import is used. Here is how to solve it: use awaitimport

What are the uses of require? What are the uses of require? Nov 27, 2023 am 10:03 AM

Usage of require: 1. Introduce modules: In many programming languages, require is used to introduce external modules or libraries so that the functions they provide can be used in the program. For example, in Ruby, you can use require to load third-party libraries or modules; 2. Import classes or methods: In some programming languages, require is used to import specific classes or methods so that they can be used in the current file; 3. Perform specific tasks: In some programming languages ​​or frameworks, require is used to perform specific tasks or functions.

Steps to solve the fatal error in the php header: require(): Failed opening required 'data/tdk.php' (include_path='.;C:\php\pear') Steps to solve the fatal error in the php header: require(): Failed opening required 'data/tdk.php' (include_path='.;C:\php\pear') Nov 27, 2023 pm 12:51 PM

Steps to resolve fatalerror:require():Failedopeningrequired'data/tdk.php'(include_path='.;C:phppear') in PHP header When developing websites or applications using PHP, we often encounter various errors . One of the common errors is "fatalerror:require():Failed

Steps to solve fatal error in php header: require(): Failed opening required 'data/tdk.php' Steps to solve fatal error in php header: require(): Failed opening required 'data/tdk.php' Nov 27, 2023 am 10:41 AM

Steps to resolve FatalError:require():Failedopeningrequired'data/tdk.php' in PHP header When developing and maintaining PHP websites, we often encounter various errors and exceptions. One of the common errors is "FatalError:require():Failedopeningrequired'data/tdk.php'".

C preprocessor? C preprocessor? Aug 27, 2023 pm 02:53 PM

C programming language supports preprocessors for efficient working of programs. The C preprocessor is a macro preprocessor for C-based programming languages. The preprocessor provides the compiler with the ability to include header files, macro expansion, conditional compilation, and line control in an explicit manner. The #hash tag is used to define preprocessors, i.e. all preprocessors start with #. This is followed by the name of the preprocessor without any spaces. Here is a list of C preprocessors. S.No. Preprocessor Description 1. #include includes specific header files from files. 2. #define defines preprocessor macros. 3. #undef Undefines the preprocessor macro 4. #if checks the compile-time condition and evaluates to a True value. 5. #else as a replacement for if preprocessor

How to avoid file inclusion vulnerability attacks in PHP language development? How to avoid file inclusion vulnerability attacks in PHP language development? Jun 09, 2023 pm 06:55 PM

With the development and popularization of the Internet, the security of web applications has become the focus of many developers. When it comes to web application security, file inclusion vulnerability attacks are a very important security issue. The vulnerability allows an attacker to manipulate the accessed application's files, which could lead to significant issues such as running malicious code or modifying data. In PHP language development, how to avoid file inclusion vulnerability attacks? The following are some common methods: 1. Set file path restrictions You can avoid file path restrictions by setting file path restrictions.

Detailed explanation of the role and usage of the require keyword in PHP Detailed explanation of the role and usage of the require keyword in PHP Jun 28, 2023 pm 11:31 PM

Detailed explanation of the role and usage of the require keyword in PHP In PHP development, require is a very commonly used keyword. Its function is to include the specified file for use by the current script. This article will explain in detail the function and use of the require keyword. 1. The role of the require keyword The require keyword can include the contents of a file into the current script. It is usually used to include some necessary external files, such as library files, configuration files, etc. Use req

How to include one php.ini file within another php.ini file? How to include one php.ini file within another php.ini file? Sep 02, 2023 pm 03:45 PM

Unable to include .ini file in main php,ini file. In contrast, when compiling PHP, the line --with-config-file-scan-dir=PATH​​​​​&a

See all articles