gpt4 book ai didi

php - 如何在 PHP 中实现 __isset() 魔术方法?

转载 作者:可可西里 更新时间:2023-10-31 22:13:01 27 4
gpt4 key购买 nike

我正在尝试使 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";

http://codepad.org/QuPNLYXP

如果出现以下情况,我怎样才能使它如此空/isset 返回 true/false:

    上面的
  • my_stuff 未设置,或者在 empty()
  • 的情况下为空或零值
  • 该方法不存在(不确定是否需要,因为我认为您无论如何都会遇到 fatal error )

?

最佳答案

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com