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!
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:
isEmpty()
and implement it thereemptyObj()
and implement it thereNo. 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;
}
}
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...
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!";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With