简体   繁体   中英

What does empty() method do when we implement ArrayAccess interface in php?

I am new to php and learning it from php.net . A note says on the following reference link that:

When using empty() ArrayAccess::offsetGet() will be called and checked if empty only if ArrayAccess::offsetExists() returns TRUE .

What does it mean?

Reference link( http://php.net/manual/en/arrayaccess.offsetexists.php ).

Hopefully this helps, way too many logic combinations don't always help though...

empty() is used to check if a value is considered 'empty', which means it either doesn't exist or the value is false ( http://php.net/manual/en/function.empty.php ).

To be able to check this in a class implementing ArrayAccess (such as a class which allows array type access - using []), this means there are two stages to this process.

Firstly - does the element exist. This is done by calling offsetExists() with the element your checking for. So with $data = [1,2]; , and you check element 2, offsetExists() will return false (only 0 and 1 have values) - which empty() will return true - as condition 1 (the item doesn't exist) is true. Called for element 1, which does exist, empty() will return false ( http://php.net/manual/en/arrayaccess.offsetexists.php ).

Secondly if the item does exist, the second part of empty() says that it's also considered empty if the value is false. offsetGet() will fetch the value from the element you are testing. So $data[true,false] , when offsetGet() is called for element 0, it will return the value at position 0 - which is the value true. Condition 2 says if the value is false, which in this case is not the case and so empty() will return false. But called for element 1, which has the value false, empty() will return true.

In case you're wondering what happens on an object that implements ArrayAccess (which is not entirely clear from the question), then here's the deal: empty() or empty-like tests (eg if ( $myObject ) ... ) will always return TRUE, and there's nothing you can do about it.

This behavior is marked as "Not a bug" in PHP's bug tracker: https://bugs.php.net/bug.php?id=62155 . The bug report is specifically about Countable , but in most situations ArrayAccess and Countable will both be implemented.

It is something to keep in mind when implementing ArrayAccess and/or Countable : it will be impossible to make your object behave exactly like an array.

For testing for empty you will have to resort to either:

  1. Implementing your own "empty-like" function, eg $myObject->isEmpty()
  2. Explicitly calling count() on the result ( Countable will have to be implemented for this to make sense).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM