[英]__isset not returning correct result
我试图使用魔术的php函数将对象链接在一起。
我有一个称为page的抽象类,并且我网站上的每个页面都扩展了该类。 在这个抽象类构造函数中,我尝试获取如下用户对象:
public function __construct( ){
$user = new user();
$this->user = $user->getIdentity();
$this->getHeader();
$this->switchAction( );
$this->getFooter();
}
现在在我的页面中,我可以使用$ this-> user,并且一切正常。 如果用户已登录,则将用户对象还给我。在我的用户类中,我有一个神奇的__get和__isset函数:
public function __get ( $name ){
switch ($name){
case 'oAlbums':
return $this->oAlbums = album::get_ar_obj($arWhere = array('user_id' => $this->id) );
break;
public function __isset ( $name ){
switch($name){
case 'oAlbums':
echo 'magic isset called, trying to call '. $name . '<br />';
return isset($this->$name);
break;
}
}
因此,在页面中时,我想通过调用$this->user->oAlbums
检查用户是否有任何专辑。 如预期的那样,这将返回一个包含所有专辑对象的数组。 但是当我这样做
if(empty( $this->user->oAlbums ))
echo 'still give smepty';
在我的页面中,它仍然回显字符串。
为什么__isset函数不起作用?
__isset
应该返回TRUE
或FALSE
。 如果变量存在并且具有值 ,则为TRUE,否则为FALSE。 您实际上是在返回$this->name
的值。 您应该只返回is_null($this->name)
。 将您的代码更改为:
public function __get ( $name ){
switch ($name){
case 'oAlbums':
return $this->oAlbums = album::get_ar_obj($arWhere = array('user_id' => $this->id) );
break;
}
}
public function __isset ( $name ){
switch($name){
case 'oAlbums':
echo 'magic isset called, trying to call '. $name . '<br />';
return !is_null($this->$name);
break;
default:
return FALSE;
}
}
$this->oAlbums
尚未在您__get()
之前设置,可能吗? 尝试:
$something = $this->user->oAlbums;
if(empty($this->user->oAlbums)) ...
...这可能说明了一些不同的地方。 在我看来,您的__isset()
应该只返回true
,而使empty()
实际上是__get()
的值。 考虑以下差异:
<?php
class foo {
function __get($name){
return $this->$name = range(1,3);
}
function __isset($name){
return isset($this->$name);
}
}
class bar {
protected $whatever = array();
function __get($name){
return $this->$name = range(1,3);
}
function __isset($name){
return isset($this->$name);
}
}
class foz {
function __get($name){
return $this->$name = range(1,3);
}
function __isset($name){
return true;
}
}
$foo = new foo();
var_dump(empty($foo->whatever));//true
$void = $foo->whatever;
var_dump(empty($foo->whatever));//false
$bar = new bar();
var_dump(empty($bar->whatever));//false
$foz = new foz();
var_dump(empty($foz->whatever));//false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.