Home  >  Article  >  Backend Development  >  The role of DIRECTORY_SEPARATOR and PATH_SEPARATOR constants in php

The role of DIRECTORY_SEPARATOR and PATH_SEPARATOR constants in php

WBOY
WBOYOriginal
2016-07-25 08:58:101030browse
This article introduces the functions of the two constants DIRECTORY_SEPARATOR and PATH_SEPARATOR in PHP. Friends in need can refer to it.

php constant 1, DIRECTORY_SEPARATOR DIRECTORY_SEPARATOR: path separator, which is ‘/’ on Linux and ‘’ on Windows

php constant 2,PATH_SEPARATOR PATH_SEPARATOR: Use to include multiple paths. Under Windows, when you need to include multiple paths, use ";" to separate them. Use ":" to separate them under Linux.

Note: The use of these two constants can avoid compatibility issues on different platforms.

For example, in zend framework, include setting index.php

<?php
set_include_path('.' . PATH_SEPARATOR . '../library/' . PATH_SEPARATOR . './application/models/'
. PATH_SEPARATOR . './application/lib/'
. PATH_SEPARATOR . get_include_path());
?>

get_include_path gets the current existing environment variables, plus the previous settings, it is the new system include.

Through this example, you can understand the usage of PATH_SEPARATOR.

Look again, DIRECTORY_SEPARATOR. PHP's internal constant, used to display the system separator command, can be used directly without any definition or inclusion.

The path separator under Windows is / (of course / can also run normally on some systems), and the path separator on Linux is. This will cause problems when deploying programs across platforms. For example, if the development machine is Windows and there is an image upload program, the designated upload file saving directory on the debugging machine is:

define(ROOT, dirname(__FILE__)."/upload");

The local debugging is normal, but after uploading to the Linux server, errors are found.

At this point, the DIRECTORY_SEPARATOR constant needs to come into play, it can be like this:

define(ROOT, dirname(__FILE__).DIRECTORY_SEPARATOR."upload");

DIRECTORY_SEPARATOR is a PHP built-in command that returns the path separator related to the operating system. It returns on Windows and returns / on Linux or Unix-like. Usually used when defining include file paths or upload saving directories.

For example:

<?php
const DIR_SEP = DIRECTORY_SEPARATOR;// 路径分割 win下\ linux下/  
private function __construct()  
{  
$this->_options = array(  
template_dir => templates . self::DIR_SEP, //模板文件所在目录  
cache_dir => templates . self::DIR_SEP . cache . self::DIR_SEP, //缓存文件存放目录  
auto_update => false, //当模板文件改动时是否重新生成缓存  
cache_lifetime => 0, //缓存生命周期(分钟),为 0 表示永久  
suffix => .html //模板文件后缀  
);  
}
?>


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