Niko Efimov Niko Efimov - 2 months ago 16
PHP Question

Evaluate object to a boolean

Consider the following:

class MyClass
{
private $var1 = "apple";
private $var2 = "orange";
}

$obj = new MyClass();

if($obj) {
// do this
}
else {
// do that
}


PHP evaluates my object to true because it has member variables. Can this logic be overridden somehow? In other words, can I have control over what an object of my class will evaluate to when treated as a boolean?

Answer

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 to true if it holds to an object. You'd have to assign one of the following to the variable first:

null
array()
""
false
0
Comments