Evaluate object to a boolean

The best you can do is using __invoke:

class MyObject {

    private $_state;

    public function __construct($state = false) {
        $this->_state = $state;
    }

    public function __invoke() {
        return $this->_state;
    }

}

$true  = new MyObject(true);
$false = new MyObject(false);

var_dump($true());   // true
var_dump($false());  // false

PHP evaluates my object to true because it has member variables.

This is incorrect. PHP actually evaluates $obj as true because it holds an object. It has nothing to do with the contents of the object. You can verify this by removing the members from your class definition, it won't make any difference in which branch of the if/else is chosen.

There is no way of making PHP evaluate a variable as false if it holds a reference to an object. You'd have to assign something "falsy" to the variable, which includes the following values:

null
array()
""
false
0

See the Converting to boolean from the PHP documentation for a list of all values that are treated as false when converted to a boolean.


No, you can't. Unfortunately boolean casting in php is not modifiable, and an object will always return true when converted to a boolean.

Since you clearly have some logic you mean to place in that control statement, why not define a method on your object (say "isValid()" ) that checks the conditions you wish to check, and then replace:

if ($obj)

with:

if ($obj->isValid())