Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate object to a boolean

Tags:

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?

like image 794
Niko Efimov Avatar asked Apr 06 '11 20:04

Niko Efimov


People also ask

How do you find the Boolean value of an object?

getBoolean(String name) returns true if and only if the system property named by the argument exists and is equal to the string "true".

How do you know if an object is boolean?

With pure JavaScript, you can just simply use typeof and do something like typeof false or typeof true and it will return "boolean" ... const isBoolean = val => 'boolean' === typeof val; and call it like!

Can a boolean be an object?

The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

How do you evaluate a boolean in Python?

Python boolean data type has two values: True and False . Use the bool() function to test if a value is True or False . The falsy values evaluate to False while the truthy values evaluate to True . Falsy values are the number zero, an empty string, False, None, an empty list, an empty tuple, and an empty dictionary.


1 Answers

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.

like image 193
meagar Avatar answered Oct 15 '22 10:10

meagar