PHP object isset and/or empty
Asked Answered
B

2

13

Is there a way to check if an object has any fields? For example, I have a soap server I am querying using a soap client and if I call a get method, I am either returned an object containing fields defining the soap query I have made otherwise I am returned object(stdClass)#3 (0) { }.

Is there a way to tell if the object has anything?

    public function get($id){
    try{
        $client = new soapclient($this->WSDL,self::getAuthorization());
        $result = $client->__soapCall('get', array('get'=> array('sys_id'=>$id)));
        if(empty($result)){$result = false; }

    }catch(SoapFault $exception){
        //echo $exception;      
        $result = false;
    } 
    return $result;
}//end get() 

This method should return either an object or false and I am only receiving an object with no fields or an object with fields.

Boomkin answered 10/8, 2010 at 14:44 Comment(0)
I
22

Updated to reflect current behavior, 5/30/12

empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:

if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {
    ...
Interleave answered 10/8, 2010 at 14:51 Comment(3)
For me, this gives an error: "PHP Fatal error: Can't use function return value in write context". AFAIK, empty() can't be used on the return value of a function, only on variables. Am I missing something?Henshaw
@MW - Only a couple of years. This answer suffered from StackOverflow dust, where answers about technology can become invalid over time. I've updated it to be more relevant, thanks for the comment!Interleave
@KevinVaughan Thanks for updating your answer! CheersBoomkin
E
-3

One of the user contributed code on the php empty() page which I think addresses your problem of checking if the array is filled but has empty values.

http://www.php.net/manual/en/function.empty.php#97772 To find if an array has nothing but empty (string) values:

<?php 
$foo = array('foo'=>'', 'bar'=>''); 
$bar = implode('', $foo); 

if (empty($bar)) { 
    echo "EMPTY!"; 
} else { 
    echo "NOT EMPTY!"; 
} 
?>
Echoism answered 10/8, 2010 at 14:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.