开发者

Explaination of while(false !== ($f=readdir($d))){

开发者 https://www.devze.com 2023-04-09 21:02 出处:网络
I have just started practicing OOP in php through the book Concepts, Techniques and Codes. Unluckily I have never worked with directories and files in PHP and feeling difficulty to understand this con

I have just started practicing OOP in php through the book Concepts, Techniques and Codes. Unluckily I have never worked with directories and files in PHP and feeling difficulty to understand this condition here is the full code

function DirectoryItems($directory){
  $d = "";
  if(is_dir($directory)){
     $d = opendir($directory) or die("Couldn't open directory.");
     while(false !== ($f=readdir($d))){
      if(is_file("$directory/$f")){
      $this->filearray[] = $f;
}
}
closedir($d);
}else{
//error
die("Must pass in a directory.");
}
}

All I can understand is first we check the parameter that is it directory after that we open that directory and than we read the direct开发者_如何学编程ory and putt all the files in the directory into an array but the condition is confusing me what the heck is !== I know only about !=

This book is written in PHP4 and 5 btw


The !== is like != but in addition to checking the equality it also checks the type.

This is an important distinction because sometimes something is "falsey" or "truthy" but not really a Boolean type with a value of false or true. The number 0 for example is generally treated as false.

The second slightly confusing part here is that the code is checking false !== (assignment) in the while loop. This is basically checking if the assignment was for a valid value.

So to out it all together code:

while(false !== ($f=readdir($d))

...translates to something like:

While $f is assigned an object from readdir($d) do ...


=== means "equal value and equal type"
!== means "not equal value or not equal type"

Using ==, and empty string is equal to false. Using === though, they are not equal because the type is different.

!= and !== work the same way. The extra = sign means that type should be checked too, not just equivalent values.


The == will coerce values to the same type to compare them. If the readdir returns 0, then False==0 will probably evaluate to be true. However, False===0 will not be true.

There are a lot of people who know a lot more about comparison operators, type coercion, value types, etc. I'll delete this when they answer.

0

精彩评论

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

关注公众号