2011-04-08 79 views
2

我剛剛發現從對象傳遞數據時empty()不起作用。這是爲什麼?從對象傳遞數據時,empty()不起作用。爲什麼?

這是我的代碼:

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

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

UPDATE
增加了對上下文的額外代碼。

// 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... 
     ) 
) 
+0

它的工作原理。我嘗試了我的自我。問題在別的地方。 – Shoe 2011-04-08 15:26:52

+0

'$ item-> description'的內容是什麼?將它分配給'$ description'時它有什麼不同? – 2011-04-08 15:27:48

+0

你可以發佈額外的上下文嗎?也就是說,如何創建'$ item','$ description'是什麼類型,您使用的是哪個版本的PHP,並且它在「不工作」時是語法錯誤? – 2011-04-08 15:35:34

回答

4

您應該閱讀文檔empty()。有一個解釋爲什麼空可能在評論中失敗。

例如,如果description是私人財產,您將設置一個魔術__get函數,但不具有魔術__isset函數。

因此,這將失敗:

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

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

,這會成功:

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"; 
} 
+0

你是絕對正確的。我愚蠢的錯誤。數據**是**私人的,這就是爲什麼我創建了'$ store-> getStoreData();'函數。 – Steven 2011-04-08 15:56:06

1

輸入:

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

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

?> 

輸出

testmetestme 

結論:它的工作原理

+0

我可以'echo $ item-> description'並且得到輸出。我可以將它分配給另一個變量。有任何想法,爲什麼它不在這裏工作? – Steven 2011-04-08 15:42:11

0

我嘗試這樣做:

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

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

它輸出:empty, string(0) ""。這意味着它的工作。如果你想嘗試一下你自己。它必須是類上下文不起作用。

相關問題