我有以下代码,但我试图将其缩短一两行,因为我认为 if
是不必要的。有什么办法可以将下面的代码缩短为单行吗?
if(file_exists($myFile))
{
$fh = fopen($myFile, 'a');
fwrite($fh, $message."\n");
}
else
{
$fh = fopen($myFile, 'w');
fwrite($fh, $message."\n");
}
最佳答案
if (file_exists($myFile)) {
$fh = fopen($myFile, 'a');
fwrite($fh, $message."\n");
} else {
$fh = fopen($myFile, 'w');
fwrite($fh, $message."\n");
}
fclose($fh);
==
if (file_exists($myFile)) {
$fh = fopen($myFile, 'a');
} else {
$fh = fopen($myFile, 'w');
}
fwrite($fh, $message."\n");
fclose($fh);
==
$fh = fopen($myFile, (file_exists($myFile)) ? 'a' : 'w');
fwrite($fh, $message."\n");
fclose($fh);
==(因为 a
检查文件是否存在,如果不存在则创建它)
$fh = fopen($myFile, 'a');
fwrite($fh, $message."\n");
fclose($fh);
==
file_put_contents($myFile, $message."\n", FILE_APPEND);
...当然,file_put_contents()
只有当它是您在给定句柄上执行的唯一写入时才会更好。如果您稍后在同一文件句柄上调用 fwrite()
,您最好使用@Pekka 的回答。
关于php - 有没有可能做比这更短的 "if file exists then append, else create new file",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8165902/