【问题标题】:Calling a function within a Class method and get data through the first function?在 Class 方法中调用函数并通过第一个函数获取数据?
【发布时间】:2018-02-06 17:03:51
【问题描述】:

您好,我如何创建一个像这样工作的类?

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

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

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

我什至拿了部分原标题对不起原海报。

【问题讨论】:

  • 不,我不明白当我有 tihs ->coupon(' 时我是如何通过 $shop->cart(function ($data){ //$data }) hello world!') 在函数的末尾。
  • 您的代码毫无意义,并且与您链接到的问题中的示例几乎没有相似之处。不完全清楚你想要什么效果,但在一个非常基本的级别“->coupon”和“->getCoupon”。这些名字至少必须匹配,当然?另外,“商店”类是什么样的?我们需要知道是否有方法“cart”、“coupon”和“getCoupon”,它们做了什么,返回了什么。

标签: php class


【解决方案1】:

您的问题有点含糊,但我认为您所说的是Fluent Interface。它们背后的想法是通过让每个方法返回实例,使您能够在单个实例上调用多个方法。它通常用于类的设置器,并且使您可以编写如下代码:

$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    相关资源
    最近更新 更多