开发者

Would it be wrong if "file_exists" was designed to return a path instead of TRUE?

开发者 https://www.devze.com 2023-02-15 19:38 出处:网络
The file_exists function returns TRUE on success but I think it woul开发者_如何学运维d be more useful if instead of just TRUE, it returned the value of the passed $filename. Am I wrong to think that?

The file_exists function returns TRUE on success but I think it woul开发者_如何学运维d 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
}


I don't see why that would be an improvement. Consider that:

  1. In practice you will put the file_exists call inside the condition, thus there will be no extra $success variable
  2. The name file_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:

$file = "dir/file.ext";
if(file_exists($file))
{
    // do something with $file
}

Or if you really need the return value later, you could do:

$file = "dir/file.ext";
if($success=file_exists($file))
{
    // do something with $file
}


Well, nothing really prevents you from writing this function:

function get_filename_if_exists($fname) {
    return (file_exists($fname) ? $fname : FALSE );
}

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)


Then what would be the use of fopen?

$res = fopen("my/path.txt");
if ($res===FALSE) {
  // File does not exists or an error while opening
}

If you specifically want to know whether a file exists then the file_exists function does what it is supposed to do.

if (FALSE===file_exists("my/path.txt")) {
  // Stop here, 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消