Reputation: 35265
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
}
Upvotes: 0
Views: 152
Reputation: 92772
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)
Upvotes: 2
Reputation: 78731
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
}
Upvotes: 3
Reputation: 212452
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
Upvotes: 4
Reputation: 28551
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,
}
Upvotes: 1
Reputation: 437554
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.
Upvotes: 5