Search code examples
phpinterfaceis-empty

Possible to implement object handling of empty()


I know we can implement PHP's countable interface to determine how the function count() works as well as the Iterator interface for using an object like an array.

Is it possible to implement some kind of interface (or any other way) to change the behavior of empty() on an object?

Essentially, this is what I would like to be able to do:

<?php
class test {
    function __empty() {
        if (count($this->data) > 0) {
            return false;
        }
        return true;
    }
}

Just a nice to have!


Solution

  • No. PHP does not have it. You can request for such feature on wiki.php.net. In the meantime you can roll your own.

    interface Empty_Checkable{
       function isempty();
    }
    
    class test implements Empty_Checkable{
        function isempty() {
            if (count($this->data) > 0) {
                return false;
            }
            return true;
        }
    }