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?
PHP User Defined FunctionsA function is a block of statements that can be used repeatedly in a program. A function will not execute automatically when a page loads. A function will be executed by a call to the function.
//define a function function myfunction($arg1, $arg2, ... $argn) { statement1; statement2; .. .. return $val; } //call function $ret=myfunction($arg1, $arg2, ... $argn);
Types of Functions in PHP. There are two types of functions as: Internal (built-in) Functions. User Defined Functions.
The function keyword is used to create a function.
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();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With