PHP - 传递给if条件的对象
问题描述:
What exactly is going on when you pass an object to an if, like this:
class TestClass {
...
}
$obj = new TestClass();
if($obj) { // what exactly is going on here ?
...
}
将对象传递给if时究竟发生了什么,如下所示: p> \ n
class TestClass {
...
}
$ obj = new TestClass();
if($ obj){//这里到底发生了什么?
.. 。
}
code> pre>
div>
答
Since your variable is an object, that will always be treated as true
- i.e. condition will always pass unless constructor of TestClass
will not instantiate object for some reason. You can see type-judging page to see how PHP handles type-casting (in this case, casting to boolean type)
答
It tells you, if your $obj
exists
答
php will convert your expression to boolean. Because this is an existing object, this will be converted to TRUE (From Php 5+, in php4 this will be converted to FALSE - I think ) :
http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting