-4

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.

BenRoob
  • 1,662
  • 5
  • 22
  • 24
PizzaSpam
  • 3
  • 3
  • Possible duplicate of [Calling a function within a Class method?](https://stackoverflow.com/questions/1725165/calling-a-function-within-a-class-method) – B001ᛦ Aug 29 '17 at 09:44
  • no i don't I do not understand how i get the data through $shop->cart(function ($data){ //$data }) when i have tihs ->coupon('hello world!') at the end of the function. – PizzaSpam Aug 29 '17 at 09:50
  • your code makes no sense and bears very little resemblance to the examples in the question you linked to. It's not entirely clear what effect you intended, but at a very basic level "->coupon" and "->getCoupon". The names must at least match, surely? Also, what does the "shop" class look like? We need to know if there are methods "cart", "coupon" and "getCoupon", and what they do, and what they return. – ADyson Aug 29 '17 at 10:00

1 Answers1

2

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.

iainn
  • 16,826
  • 9
  • 33
  • 40