小编典典

PHP方法链接?

php

我正在使用PHP 5,并且听说过面向对象方法中的一项新功能,即“方法链接”。究竟是什么?如何实施?


阅读 342

收藏
2020-05-26

共1个答案

小编典典

实际上,它相当简单,您有一系列的mutator方法,它们都返回原始(或其他)对象,这样您就可以继续在返回的对象上调用方法。

<?php
class fakeString
{
    private $str;
    function __construct()
    {
        $this->str = "";
    }

    function addA()
    {
        $this->str .= "a";
        return $this;
    }

    function addB()
    {
        $this->str .= "b";
        return $this;
    }

    function getStr()
    {
        return $this->str;
    }
}


$a = new fakeString();


echo $a->addA()->addB()->getStr();

输出“ ab”

在线尝试!

2020-05-26