5

I saw some sample php scripts can use a function after one another, but I can't find how to write script like that.

When I write the php script:

class apple {
  function banana() {
    echo 'Hi!';
  }
}

It looks like this when I want to call the function banana:

$apple = new apple;
$apple->banana();

What if I want to call a function right after the previous one, like this:

$apple->banana()->orange()

I've tried to put an function inside another, but it returns with error. How can I write the script like this?

timo
  • 95
  • 4

2 Answers2

6

This code is to improve your method chaining,

    <?php

    class Fruits
    {
        public function banana()
        {
            echo 'Hi i am banana!'.'<br>';
            return $this;
        }

        public function orange()
        {
            echo 'Hi i am orange!'.'<br>';
            return $this;
        }

        public function __call($mName,$mValues)
        {
            echo 'Hi i am '.$mName.'!'.'<br>';
            return $this;
        }
    }

    $fruits = new Fruits();
    $fruits->banana()->orange()->grape()->avocado();
Crunch Much
  • 1,537
  • 1
  • 11
  • 14
4

You can do something like this:

class apple {
  public function banana() {
    echo 'Hi!';
    return $this;
  }
  public function orange() {
      echo 'Hi from orange';
      return $this;
  }
}

$apple = new apple;
$apple->banana()->orange();

This is a shortcut to something like this:

$apple = new apple;
$same_apple = $apple->banana();
// $apple and $same_apple are the same thing here.
$still_the_same_apple = $same_apple->orange(); 

In the end, $apple and $still_the_same_apple are the same instance you created in the first place.

MikeWu
  • 3,042
  • 2
  • 19
  • 27
  • What's the difference of `$apple = new apple;` and `$apple = new apple();`? – timo Nov 01 '15 at 05:16
  • There is no difference if you don't want to supply constructor arguments. There is a discussion about this here: http://stackoverflow.com/questions/3873111/instantiate-a-class-with-or-without-parentheses – MikeWu Nov 01 '15 at 05:20