PHP怎么判断对象为空
在PHP中,有时候需要判断一个对象会不会为空,这个时候我们可使用以下方法:
1.isset()
isset()是PHP中一个非常经常使用的函数,通经常使用于判断一个变量会不会声明和赋值,但是它也能够用于对象。如果一个对象被赋值了,它就不为空,isset()函数会返回true,否则返回false。
$obj=newstdClass();var_dump(isset($obj));//bool(true)
2.empty()
empty()是PHP中另外一个经常使用的函数,用于判断一个变量会不会为空,通经常使用于字符串、数组和对象。当一个对象为空时,empty()函数会返回true,否则返回false。
$obj=newstdClass();var_dump(empty($obj));//bool(true)
3.is_null()
is_null()函数用于判断一个变量会不会为null,如果一个对象为null,is_null()函数会返回true,否则返回false。
$obj=null;var_dump(is_null($obj));//bool(true)
4.count()
count()函数可以用于数值数组、关联数组和对象。当一个对象为空时,count()函数会返回0,否则返回对象中元素的个数。
$obj=newstdClass();var_dump(count($obj));//int(0)
5.property_exists()
property_exists()函数用于检查一个对象会不会具有指定的属性。如果对象具有该属性,property_exists()函数会返回true,否则返回false。
classTest{public$name;}$obj=newTest();var_dump(property_exists($obj,'name'));//bool(true)
6.method_exists()
method_exists()函数用于检查一个对象会不会具有指定的方法。如果对象具有该方法,method_exists()函数会返回true,否则返回false。
classTest{publicfunctionhello(){echoHelloWorld!;}}$obj=newTest();var_dump(method_exists($obj,'hello'));//bool(true)
7.instanceof
instanceof运算符用于检查一个对象会不会属于指定的类或类的子类。如果对象属于指定类或类的子类,instanceof运算符会返回true,否则返回false。
classParentClass{publicfunctionhello(){echoHelloWorld!;}}classChildClassextendsParentClass{}$obj=newChildClass();var_dump($objinstanceofParentClass);//bool(true)
桂<哥<网<络www.guIgege.cn
TOP