PHP链接方法

1 php methods chaining

class AAA

{

    function getRealValue($var)
    {
        $this->var = $var;
        return $this;
    }

    function asString()
    {
        return (string) $this->var;
    }

}

$a = new AAA;
$a->getRealValue(30); 
$a->getRealValue(30)->asString(); 
Run Code Online (Sandbox Code Playgroud)

因此,当我调用$ a-> getRealValue(30)时,它应该返回30,

但是当我调用$ a-> getRealValue(30) - > asString()时,它应该返回'30'作为字符串'.

谢谢

Gor*_*don 6

因此,当我调用$ a-> getRealValue(30)时,它应该返回30,但是当我调用$ a-> getRealValue(30) - > asString()时,它应该返回'30'作为字符串'.

这是不可能的(尚未).当getRealValue返回一个标值,你不能调用它的方法.

除此之外,你的课程对我来说没什么意义.调用您的方法getRealValue但它接受一个参数并设置该值.所以它应该被称为setRealValue.方法链接在一边,你可能在寻找ValueObject吗?

class Numeric
{
    private $value;

    public function __construct($numericValue)
    {
        if (false === is_numeric($numericValue)) {
            throw new InvalidArgumentException('Value must be numeric');
        }
        $this->value = $numericValue;
    }

    public function getValue()
    {
        return $this->value;
    }

    public function __toString()
    {
        return (string) $this->getValue();
    }
}

$fortyTwo = new Numeric(42);
$integer = $fortyTwo->getValue(); // 42
echo $fortyTwo; // "42"
Run Code Online (Sandbox Code Playgroud)