2017-08-29 79 views
-4

嗨我如何创建一个类似这样的类?在Class方法中调用函数并通过第一个函数获取数据?

$shop = new shop(); 
$shop->cart(function ($data){ 
    //$data 
})->coupon('hello world!'); 

$shop->getCoupon(); //hello world! 

那么我该怎么做?我玩过Calling a function within a Class method?的例子

我甚至把部分原始标题对不起原来的海报。

+0

[在类方法中调用函数?](https://stackoverflow.com/questions/1725165/calling-a-function-within-a-class-method) –

+0

不可以我不我当我在函数结尾处有tihs - > coupon('hello world!')时,我不明白数据是如何通过$ shop-> cart(function($ data){ } – PizzaSpam

+0

你的代码没有任何意义,并且与你链接到的问题中的例子几乎没有相似之处。目前还不完全清楚你的目标是什么,但是在一个非常基本的层面上 - “优惠券”和“ - > getCoupon”。名字必须至少匹配,当然?此外,“商店”类是什么样的?我们需要知道是否有方法“购物车”,“优惠券”和“getCoupon”,以及他们做什么,他们返回什么。 – ADyson

回答

2

你的问题有点含糊,但我认为你所说的是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举例。

+0

谢谢,我想我得到它在我的狗屎fest代码:) – PizzaSpam

相关问题