How to define this php function?

I saw how some php script examples can use the function one after another, but I cannot find how to write a script like this.

When I write a php script:

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

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

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

What if I want to call a function immediately after the previous one, for example:

$ apple trees> banana () → orange ()

I tried to put the function inside another, but it returns with an error. How can I write a script as follows?

+5
source share
2 answers

This code is intended to improve the chain of methods,

  <?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(); 
+6
source

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 for 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(); 

After all, $ apple and $ still_the_same_apple are the same instance that you created in the first place.

+4
source

Source: https://habr.com/ru/post/1234938/


All Articles