如果“file_exists”是错误的被设计为返回路径而不是 TRUE?
file_exists 函数成功时返回 TRUE,但我认为如果它返回值而不只是 TRUE,会更有用传递的$filename
。我这样想有错吗?
如果函数是这样设计的,我们就可以使用:
$file = file_exists("dir/file.ext");
if($file)
{
// do something
}
... 而不是更复杂的:
$file = "dir/file.ext";
$success = file_exists("dir/file.ext");
if($success)
{
// do something
}
The file_exists function returns TRUE on success but I think it would be more useful if instead of just TRUE, it returned the value of the passed $filename
. Am I wrong to think that?
If the function was designed like that, we would be able to use:
$file = file_exists("dir/file.ext");
if($file)
{
// do something
}
... instead of the more complicated:
$file = "dir/file.ext";
$success = file_exists("dir/file.ext");
if($success)
{
// do something
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不明白为什么这会是一个改进。请考虑:
file_exists
调用放在条件内,因此不会有额外的$success
变量file_exists
预先决定了代码的读者认为该函数将返回是/否答案(布尔值)所以总之,我认为除了返回值的类型之外什么都不改变是一个坏主意。
I don't see why that would be an improvement. Consider that:
file_exists
call inside the condition, thus there will be no extra$success
variablefile_exists
predisposes the reader of the code that the function will return a yes/no answer (boolean value)So in conclusion, I think that it would be a bad idea to change nothing but the type of the return value.
文件存在吗?基本上是一个是或否问题,因此它给出是或否(布尔)答案。
该文件存在吗? “是”,它存在。
所以它的名字恰如其分
file_exists? is basically a yes or no question, so it gives a yes or no (boolean) answer.
Does the file exist? "Yes", it exists.
So it's aptly named for what it does
那毫无意义。它还可以返回文件权限、文件大小、最后修改日期,而且它仍然与文件名一样有意义。它只不过是一个给出布尔值的检查,你可以根据它做出决定。
顺便说一句,我没有得到你的例子,有什么比以下更容易的:
或者如果你以后确实需要返回值,你可以这样做:
That would just make no sense. It could also return the file permissions, the file size, the last modified date, and still it would make as much sense as the filename. It is nothing but a check that gives a Boolean value, and you can make decisions based on it.
By the way, I don't get your examples, what could be easier than:
Or if you really need the return value later, you could do:
好吧,没有什么能真正阻止您编写这个函数:
恕我直言,它是有问题的,因为它有多种返回类型,并且不会为您提供比从
file_exists()
获得的更多信息 - 因此比毫无意义更糟糕;但如果你真的愿意的话,也可以这样搬起石头砸自己的脚。(由于此处和其他答案中所述的原因,这种行为不太可能被改进到
file_exists()
中)Well, nothing really prevents you from writing this function:
It is IMHO problematic as it has multiple return types, and doesn't give you any more information than you'd get from
file_exists()
- and therefore worse than pointless; but it is possible to shoot yourself in the foot like this, if you really want.(this behavior is unlikely to get retrofitted into
file_exists()
, for the reasons stated here and in the other answers)那么fopen有什么用呢?
如果您特别想知道文件是否存在,那么 file_exists 函数会执行它应该执行的操作。
Then what would be the use of fopen?
If you specifically want to know whether a file exists then the file_exists function does what it is supposed to do.