我正在尝试设置一些可在实例化和静态上下文中调用的 PHP 方法。有什么好的方法可以做到这一点?例如我希望能够做到:
Foo::bar($item);
foo($item)->bar();
我可以设置两个单独的类,并让每个函数修改 thisArg 并委托给另一个,但似乎必须有更好的方法。我能想到的唯一方法是只用一个类来做到这一点:
function foo($item = null) {
return $item instanceof Foo ? $item : new Foo($item);
}
class Foo {
protected $wrapped;
public function __construct($item = null) {
$this->wrapped = $item;
}
public function get() {
return $this->wrapped;
}
public function bar($item = null) {
isset($this) and $item = &$this->wrapped;
// do stuff with $item
return isset($this) ? $this : $item;
}
}
如果您查看underscore.php的代码,他们会执行类似的操作。我已经阅读了一些相关的问题,这些问题指出使用isset($this)
来确定上下文可以引发警告,但它似乎工作正常......对此有任何更新的想法吗?另一种可能性是创建两个类,一个具有所有静态版本的方法,然后另一个类使用__call委托给静态方法,例如:
class _Foo
{
protected $wrapped;
public function __construct($item = null) {
$this->wrapped = $item;
}
public function __call($method_name, $args) {
array_unshift($args, $this->wrapped);
$this->wrapped = call_user_func_array('Foo::' . $method_name, $args);
return $this;
}
}
想法?