你的问题有点含糊,但我认为你所说的是Fluent Interface。它们背后的想法是使您能够通过让每个方法返回实例来调用单个实例上的多个方法。它通常用于在类的setter方法,使您写这样的代码:
$foo = new Foo();
$foo
->setThisThing()
->setAnotherThing()
->setThingToParameter($parameter)
...;
而不是
$foo->setThisThing();
$foo->setAnotherThing();
...
不管你觉得这是好还是坏是一个品味的问题,but Fluent interfaces do come some drawbacks
在你的情况下,商店类可能看起来像:
<?php
class shop
{
private $couponText;
public function cart($function) {
// Do something with $function here
return $this;
}
public function coupon($couponText) {
$this->couponText = $couponText;
return $this;
}
public function getCoupon() {
return $this->couponText;
}
}
关键部分是return $this;
行 - 它们允许您将后续的方法调用链接到彼此上,如您的示例中所示。
查看https://eval.in/851708举例。
[在类方法中调用函数?](https://stackoverflow.com/questions/1725165/calling-a-function-within-a-class-method) –
不可以我不我当我在函数结尾处有tihs - > coupon('hello world!')时,我不明白数据是如何通过$ shop-> cart(function($ data){ } – PizzaSpam
你的代码没有任何意义,并且与你链接到的问题中的例子几乎没有相似之处。目前还不完全清楚你的目标是什么,但是在一个非常基本的层面上 - “优惠券”和“ - > getCoupon”。名字必须至少匹配,当然?此外,“商店”类是什么样的?我们需要知道是否有方法“购物车”,“优惠券”和“getCoupon”,以及他们做什么,他们返回什么。 – ADyson