作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在尝试使 empty()
和 isset()
等函数处理方法返回的数据。
我目前拥有的:
abstract class FooBase{
public function __isset($name){
$getter = 'get'.ucfirst($name);
if(method_exists($this, $getter))
return isset($this->$getter()); // not working :(
// Fatal error: Can't use method return value in write context
}
public function __get($name){
$getter = 'get'.ucfirst($name);
if(method_exists($this, $getter))
return $this->$getter();
}
public function __set($name, $value){
$setter = 'set'.ucfirst($name);
if(method_exists($this, $setter))
return $this->$setter($value);
}
public function __call($name, $arguments){
$caller = 'call'.ucfirst($name);
if(method_exists($this, $caller)) return $this->$caller($arguments);
}
}
用法:
class Foo extends FooBase{
private $my_stuff;
public function getStuff(){
return $this->my_stuff;
}
public function setStuff($stuff){
$this->my_stuff = $stuff;
}
}
$foo = new Foo();
if(empty($foo->stuff)) echo "empty() works! \n"; else "empty() doesn't work:( \n";
$foo->stuff = 'something';
if(empty($foo->stuff)) echo "empty() doesn't work:( \n"; else "empty() works! \n";
如果出现以下情况,我怎样才能使它如此空/isset 返回 true/false:
my_stuff
未设置,或者在 empty()
?
最佳答案
public function __isset($name){
$getter = 'get'.ucfirst($name);
return method_exists($this, $getter) && !is_null($this->$getter());
}
此检查是否存在$getter()
(如果不存在,则假定该属性也不存在)并返回一个非空值。所以 NULL
将导致它返回 false,正如您在阅读 isset()
的 php 手册后所期望的那样。 .
关于php - 如何在 PHP 中实现 __isset() 魔术方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6242591/
我需要了解魔术函数 __isset() 和普通函数 isset()。实际上 php 语言构造 isset() 和 php 魔术方法 __isset() 之间的真正区别是什么?当我用谷歌搜索时,他们告诉
我正在尝试使 empty() 和 isset() 等函数处理方法返回的数据。 我目前拥有的: abstract class FooBase{ public function __isset($na
我有一个抽象父类 Mongo_Document(来自 mongodb-php-odm)和一个继承类 Model_ActionPlan。 Mongo_Document 具有神奇的 __isset 和 _
我是一名优秀的程序员,十分优秀!