Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 732
teynon Avatar asked Jan 28 '13 18:01

teynon


4 Answers

No there is not. The iterator behavior and count behaviors have no sense over an object; that's why you can override them. The default behavior of empty() applied to an object has a meaning instead: is it an instance of an object or is it NULL?; that's why you can't override it.

You can instead:

  • create a method inside the object called isEmpty() and implement it there
  • create a global function emptyObj() and implement it there
like image 61
Shoe Avatar answered Nov 19 '22 21:11

Shoe


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;
    }
}
like image 30
Shiplu Mokaddim Avatar answered Nov 19 '22 19:11

Shiplu Mokaddim


This is not possible on the object directly.

If you need to do it, I would suggest implementing the Countable interface, and then instead of calling empty($foo), call count($foo) == 0...

However, for properties, it is possible using a combination of two magic methods: __isset and __get. For example:

class Foo {
    protected $bar = false;
    protected $baz = true;
    public function __get($key) {
        return $this->$key;
    }
    public function __isset($key) {
        return isset($this->$key);
    }
}

That results in:

empty($foo->abc); // true, isset returns false
empty($foo->bar); // true, isset returns true, but get returns false value
empty($foo->baz); // false, isset returns true, and get returns a true value

So no, it's not possible with a single method handler, but with the combination of the two magic methods, it works fine...

like image 45
ircmaxell Avatar answered Nov 19 '22 19:11

ircmaxell


It is possible to implement Countable

class MyCollection extends stdClass implements Serializable, ArrayAccess, Countable, Iterator, JsonSerializable
{
    public function count() {
        return count($this->array);
    }
}

and use !count() instead of empty() like

if (!count($myList)) {
    echo "List is empty!";
}
like image 38
Fusca Software Avatar answered Nov 19 '22 20:11

Fusca Software