看来您正在做的是将函数应用程序的前缀符号转换为中缀符号。也就是说,你写的是x1->f(x2,…,xn),而不是f(x1,x2,…,xn)。
您始终可以只使用前缀表示法来编写S::UcLast(S::UcFirst("my string"))。简洁来自use Utils\String as S。
要将-> 用作中缀表示法的一部分,您需要一个如下所示的类定义(我假设您的实现也是这样的)。
class UtilStringProxy
{
public $string;
public function __construct($string)
{
$this->string = $string;
}
public function UcFirst()
{
$this->string = S::UcFirst($this->string);
return $this;
}
public function UcLast()
{
$this->string = S::UcLast($this->string);
return $this;
}
public function Suffix($suffix)
{
$this->string = S::Suffix($this->string, $suffix);
return $this;
}
}
第一个论点被剥离。这就是我们如何将f 置于中缀位置(在操作数 1 和 2 之间)。然后你可以写:
(new UtilStringProxy("my string"))->UcFirst()->UcLast()->Suffix("New")->string
就我个人而言,我并没有看到这个愿望:
S::Suffix(S::UcLast(S::UcFirst("my string")), "New")
附录
函数组合是查看这一点的另一种方式。函数应用程序提供从左到右的读数,而函数组合可以通过翻转参数为您提供从左到右或从右到左的读数。
UtilStringProxy 的示例基本上是为特定函数集 UcFirst, UcLast, Suffix 定义的从左到右的函数组合。你可以从中概括。
class Compose
{
public $f;
public function __construct(callable $f)
{
$this->f = $f;
}
public function lr(callable $g)
{
$f = $this->f;
return new Compose(function ($x) use ($f, $g) {
return $g($f($x));
});
}
public function rl(callable $g)
{
$f = $this->f;
return new Compose(function ($x) use ($f, $g) {
return $f($g($x));
});
}
public function call($x)
{
$f = $this->f;
return $f($x);
}
}
我添加了call 方法,因为PHP 在其解析器中存在一个不幸的弱点,因此您不能编写expr(x) 来将expr 应用于x 以用于任何表达式——只有一些。如果您只想返回组合函数,请使用->f,如果您想立即应用它,请使用->call(x)。
使用这个你可以写从左到右的作文:
(new Compose('strtolower'))->lr('ucfirst')->call("hEllo World")
或从右到左合成:
(new Compose('ucfirst'))->rl('strtolower')->call("hEllo World")