0

私はこのコードを持っています:

class one{
    public $instance;

    function instance(){
        $this->instance = 'instance was created';
    }

    function execute(){
        $this->instance .= "and something happened";
    }
}

$class = new one;

$class->instance();
$class->execute();

echo $class->instance;

そして、それは私が期待することを行いますが、アクションを連鎖させるにはどうすればよいですか。たとえば、これらの関数を1行で呼び出すにはどうすればよいですか:

$class->instance()->execute();

そして、私は次のようにすることが可能であることを知っています:

one::instance()->execute();

しかし、この場合、物事を複雑にする静的関数が必要になります。これらのことについて説明が必要です

4

4 に答える 4

2

$thisチェーンを機能させるには、チェーン可能にしたい各メソッドから戻る必要があります。

class one{
    public $instance;

    function instance(){
        $this->instance = 'instance was created';
        return $this;
    }

    function execute(){
        $this->instance .= "and something happened";
        return $this;
    }
}

また、プロパティにメソッドと同じ名前を付けることもお勧めできません。パーサーにとっては明白かもしれませんが、開発者にとっては混乱を招きます。

于 2012-10-02T18:15:32.777 に答える
1

チェーン化の一般的なアプローチは、チェーン化する必要があるすべてのメソッド$thisの として返すことです。returnしたがって、コードの場合、次のようになります。

class one{
    public $instance;

    function instance(){
        $this->instance = 'instance was created';
        return $this;
    }

    function execute(){
        $this->instance .= "and something happened";
        return $this;
    }
}

だからあなたは冷たいです:

$one = new one;
$one->instance()->execute(); // would set one::instance to 'instance was createdand something happened'
$one->instance()->instance()->instance(); // would set one::instance to 'instance was created';
$one->instance()->execute()->execute(); / would set one::instance to 'instance was createdand something happenedand something happened'
于 2012-10-02T18:20:01.787 に答える
0

関数の最後でインスタンスを返す必要があります。

class one{
    public $instance;

    function instance(){
        $this->instance = 'instance was created';
        return $this;
    }

    function execute(){
        $this->instance .= "and something happened";
        return $this;
    }
}

その後、それらを連鎖させることができます。

ところで、これはおそらく単なるサンプル コードですが、instance関数は実際にはインスタンスを作成しません ;)

于 2012-10-02T18:15:57.393 に答える
0

$class->instance()->execute();

動作するはずですが、メソッドで値を返す必要があります。

于 2012-10-02T18:16:46.490 に答える