Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

php - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...