douci2022 2017-08-29 09:42
浏览 72
已采纳

在Class方法中调用函数并通过第一个函数获取数据?

Hi how do i create a class that works like this?

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

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

so how do i do this? i have played around with examples from Calling a function within a Class method?

i even took parts of the original title sorry original poster.

  • 写回答

1条回答 默认 最新

  • dow56114 2017-08-29 10:14
    关注

    Your question is a bit vague, but I think what you are talking about is a Fluent Interface. The idea behind them is to enable you to call multiple methods on a single instance, by having each method return the instance. It's commonly used for setters on classes, and enables you to write code like:

    $foo = new Foo();
    $foo
        ->setThisThing()
        ->setAnotherThing()
        ->setThingToParameter($parameter)
        ...;
    

    rather than

    $foo->setThisThing();
    $foo->setAnotherThing();
    ...
    

    Whether you find this better or worse is a matter of taste, but Fluent interfaces do come some drawbacks

    In your case, the shop class might look like:

    <?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;
      }
    }
    

    The key parts are the return $this; lines - they allow you to chain subsequent method calls onto each other, as in your example.

    See https://eval.in/851708 for an example.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制