开发者

empty() does not work when passing data from an object. Why?

开发者 https://www.devze.com 2023-02-22 21:06 出处:网络
I just discovered that empty() does not work when passing data from an object. Why is that? This is my code:

I just discovered that empty() does not work when passing data from an object. Why is that?

This is my code:

// This works
$description = $store->description;
if (!empty($description) )
  echo $description;

//This is not working
if (!empty($store->description) )
  echo $store->description;

UPDATE

Adde开发者_开发知识库d extra code for context.

// At the top of my PHP file I have this code
$store = Factory::new_store_obj($id);

// To controll that I got content, I can test by printing object
echo '<pre>';
print_r($store);
echo '</pre>';

//output
Store Object
(
    [data:Store:private] => Array
        (
            [name] => Lacrosse
            [street1] => Bygdøy Allé 54
            [street2] => 
            [zipcode] => 0265
            [city] => Oslo
            [country] => Norway
            [phone] => 22441100
            [fax] => 
            [email] => 
            [opening_hours] => 
            [keywords] => 
            [description] => Lacrosse er en bla bla bla...
        )
)


You should read the docs for empty(). There is an explanation of why empty might fail in the comments.

For example you will get this error if description is a private property, you have set up a magic __get function without the magic __isset function.

So this will fail:

class MyClass {
    private $foo = 'foo';
    public function __get($var) { return $this->$var; }
}

$inst = new MyClass;
if(empty($inst->foo))
{
    print "empty";
}
else
{
    print "full";
}

and this will succeed:

class MyClass {
    private $foo = 'foo';
    public function __get($var) { return $this->$var; }
    public function __isset($var) { return isset($this->$var); }
}

$inst = new MyClass;
if(empty($inst->foo))
{
    print "empty";
}
else
{
    print "full";
}


input:

<?php
$item->description = "testme";
$description = $item->description;
if (!empty($description) )
  echo $description;

//This is not working
if (!empty($item->description) )
  echo $item->description;

?>

output

testmetestme

conclusion: it works


I tried this:

class test {
    private $var = '';
    public function doit() {
        echo (empty($this->var)) ? 'empty' : 'not';
        echo '<br>';
        var_dump($this->var);
    }
}

$t = new test;
$t->doit();

It outputs: empty, string(0) "". This means that it works. Try it your self if you want. It must be the class context not working.

0

精彩评论

暂无评论...
验证码 换一张
取 消