gpt4 book ai didi

PHP 方法链还是流利的接口(interface)?

转载 作者:IT老高 更新时间:2023-10-28 11:43:16 24 4
gpt4 key购买 nike

我正在使用 PHP 5,并且听说了面向对象方法中的一个新特性,称为“方法链”。究竟是什么?如何实现?

最佳答案

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

<?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”

Try it online!

关于PHP 方法链还是流利的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3724112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com