The correct usage of the require () file contained in PHP

Source: Internet
Author: User
Tags php file php and php framework relative require root directory

Before looking at some PHP framework source code, very strange in the file contains, will use DirName (__file__) to patchwork file path, do not know what the benefits, then finally found the reason.

Let's look at a simple example:

There are a,b,c three PHP files. A.php in the site root directory, b.php under the B folder--b/b.php,c.php under the C folder--c/c.php. Some confusion? Look at the picture is at a glance:

A.php and b.php all contain c.php, and finally c.php contains a PHP file--d/d.php under the D folder.

Let's look at a.php first:

<?php 
    
    $file _name = ' a.php ';
    
    echo "This is a.php";
    echo "

Very simple code, printed after the output, contains the c/c.php, and then we need to look at c/c.php:

<?php 
    $c _file_name = ' c.php ';
    
    Echo ' This is c.php, are required by '. $file _name;
    echo "

PrintOut "This is c.php, are required by a.php", $file _name are variables defined in a.php. In the end, it contains the d.php. Because the D folder is on the top level of the current c.php file, as a matter of common sense, we will naturally write the path as "... /d/d.php ". But unfortunately, it will be an error. The reason is that in the included file, such as c.php, and then to include other files, the path is relative to the outermost parent file, that is, relative to a.php, you can understand that because you are included in me, so you have to take me as the subject. Looks very iffy, the principle is actually very simple: you can put require (' c/c.php '); Look at the code in the c/c.php file so that our a.php looks like this:

<?php 
    $file _name = ' a.php ';
    
    echo "This is a.php";
    echo "

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.