Solution rollup for include paths in PHP

Source: Internet
Author: User

After a few days of sorting through a messy code, it became aware that PHP is not generally cheap for include processing: Other programming languages use the currently processed file as a benchmark when dealing with relative directories in include. In other words, if a contains a b,b containing C, c then contains a file with a relative path, then the path is relative to C. Such a process is natural, consistent with people's intuition and facilitates the development of path-independent packages.

But PHP does not, it is preferred relative to the working directory to handle, and if the path contains. .. , it is only relative to the working directory.
Perhaps the PHP processing has its reason, who knows may as well tell me.

Here are a few ways to solve this problem:

    • __file__

__file__ always equals to the real path of a PHP script regardless whether it ' s included.

__FILE__ helps you specify the file to include using relative path to the including FILE.
This method is preferred recommendation. Although your include statement will therefore have to write a bit longer, but a word, value!

<?php This article is from: http://www.87717.com

Include DirName (__file__). /subdir ';

DirName return value does not contain the trailing slash


?>


    • $_server[' document_root ']

This method allows your to specify a path relative to the Web server Doc_root for file inclusion.
This is also a good way to use many projects, in my opinion, the disadvantage is that the whole project is not convenient to move.

For example, when you first place it in the xxx.com/, and then you need to put it under xxx.com/abc/, you have to change the file (calculate the location of root in a public file, and other files contain this common file).
Especially when you have multiple parts of the same code (such as a test environment and a formal environment), you can change the file.

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.