我刚刚发现从对象传递数据时empty()
不起作用。那是为什么?
这是我的代码:
// This works
$description = $store->description;
if (!empty($description) )
echo $description;
//This is not working
if (!empty($store->description) )
echo $store->description;
更新
为上下文添加了额外的代码。
// 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 :(得分: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";
}
答案 1 :(得分: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
结论:它有效
答案 2 :(得分: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) ""
。这意味着它有效。如果你愿意,可以尝试自己。它必须是类上下文不起作用。