Is it possible to chain function calls in PHP?

时间:2015-06-26 10:04:55

标签: php

If I have this functions

function function1 ( $myParameter ) {
...
}

function function2 ( $myParameter ) {
...
}

function function3 ( $myParameter ) {
...
}

When I call

function1( function2( function3( $myParameter ) ) )

I would like to call like this:

function3( $myParameter ) -> function2() -> function1()

function3( $myParameter ) is sent as parameter to function2()

A PHP plugin exists (or something else) ?

Thx

2 个答案:

答案 0 :(得分:2)

You can chained objects methods by returning an instance (with $this) Here is a trivial example.

class foo {
    function function1() {
        echo "I'm function1\n";
        return $this;
    }
    function function2() {
        echo "I'm function2\n";
        return $this;
    }
    function function3() {
        echo "I'm function3\n";
        return $this;
    }
}


$bar = new foo();
$bar->function3()->function2()->function1();

答案 1 :(得分:0)

You could achieve this by setting up the functions on an object. Since I don't know the domain it's hard to say how sane this is, however if it's just the code formatting you're interested in. you could use this.

<?php

class Functions
{
    protected $value;

    public function function1($param)
    {
        //do something
        return $this->value;
    }

    public function function2($param)
    {
        // do something to $this->value 
        return $this;
    }

    public function function3($param)
    {
        // do something to $this->value
        return $this;
    }
}

$class = new Functions();
$param = 'someVariable';

$result = $class->function3($param)->function2($param)->function1($param);

Again without knowing the domain it's hard to know how sensible this approach is