Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define this kind of php function?

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?

like image 789
timo Avatar asked Nov 01 '15 04:11

timo


People also ask

How will you define a function in PHP?

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.

How do you define a function in PHP give an example?

//define a function function myfunction($arg1, $arg2, ... $argn) { statement1; statement2; .. .. return $val; } //call function $ret=myfunction($arg1, $arg2, ... $argn);

What is type of function in PHP?

Types of Functions in PHP. There are two types of functions as: Internal (built-in) Functions. User Defined Functions.

Which keyword is used to define function in PHP?

The function keyword is used to create a function.


1 Answers

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();
like image 157
Neel Ion Avatar answered Oct 09 '22 14:10

Neel Ion