什么时候使用php_ol是一个好主意?
我有时会在PHP代码示例中看到这种情况。这是否处理DOS/Mac/Unix终端线问题?
什么时候使用php_ol是一个好主意?
我有时会在PHP代码示例中看到这种情况。这是否处理DOS/Mac/Unix终端线问题?
当前回答
PHP_EOL的定义是,它为您提供正在操作的操作系统的换行符。
在实践中,您几乎不需要这个。考虑以下几个案例:
When you are outputting to the web, there really isn't any convention except that you should be consistent. Since most servers are Unixy, you'll want to use a "\n" anyway. If you're outputting to a file, PHP_EOL might seem like a good idea. However, you can get a similar effect by having a literal newline inside your file, and this will help you out if you're trying to run some CRLF formatted files on Unix without clobbering existing newlines (as a guy with a dual-boot system, I can say that I prefer the latter behavior)
PHP_EOL太长了,真的不值得使用。
其他回答
在某些系统上,使用这个常量可能是有用的,因为如果,例如,您正在发送电子邮件,您可以使用PHP_EOL让跨系统脚本在更多系统上工作…但即使它是有用的,有时你会发现这个常数未定义,现代主机与最新的php引擎没有这个问题,但我认为一件好事是写一些代码来挽救这种情况:
<?php
if (!defined('PHP_EOL')) {
if (strtoupper(substr(PHP_OS,0,3) == 'WIN')) {
define('PHP_EOL',"\r\n");
} elseif (strtoupper(substr(PHP_OS,0,3) == 'MAC')) {
define('PHP_EOL',"\r");
} elseif (strtoupper(substr(PHP_OS,0,3) == 'DAR')) {
define('PHP_EOL',"\n");
} else {
define('PHP_EOL',"\n");
}
}
?>
所以你可以毫无问题地使用php_ol…很明显,PHP_EOL应该在脚本上使用,应该在多个系统上同时工作,否则你可以使用\n或\r或\r\n…
备注:PHP_EOL可以为
1) on Unix LN == \n
2) on Mac CR == \r
3) on Windows CR+LN == \r\n
希望这个答案能有所帮助。
您正在编写主要使用单引号字符串的代码。
echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL;
echo 'this other $one'."\n";
PHP_EOL的定义是,它为您提供正在操作的操作系统的换行符。
在实践中,您几乎不需要这个。考虑以下几个案例:
When you are outputting to the web, there really isn't any convention except that you should be consistent. Since most servers are Unixy, you'll want to use a "\n" anyway. If you're outputting to a file, PHP_EOL might seem like a good idea. However, you can get a similar effect by having a literal newline inside your file, and this will help you out if you're trying to run some CRLF formatted files on Unix without clobbering existing newlines (as a guy with a dual-boot system, I can say that I prefer the latter behavior)
PHP_EOL太长了,真的不值得使用。
当你想要一个新的行,并且你想跨平台的时候,你可以使用PHP_EOL。
这可能发生在将文件写入文件系统时(日志、导出、其他)。
如果您希望生成的HTML具有可读性,则可以使用它。所以可以在<br />后面加上PHP_EOL。
如果你在cron上运行php脚本,你需要输出一些东西,并将其格式化后显示在屏幕上,你就可以使用它。
如果你要发送一封需要一些格式的电子邮件,你可以使用它。
当我的PHP没有浏览器时,我使用PHP_EOL常量。实际上,我间接地使用它。查看下面的示例。 例如,有一个叫code的网站。Golf(基本上是堆栈交换代码,但具有交互性)。有一个PHP只有控制台输出,我需要使用PHP_EOL常量来使用这个。
一种缩短它的方法是,一旦你需要使用PHP_EOL常量,就像这样做:
<?php
echo $n = PHP_EOL;
?>
这声明了变量$n,您可以使用它代替PHP_EOL常量作为换行符。甚至比<br>还要短,而且几乎任何需要换行符的东西都可以使用$n !