PHP链接方法


PHP Chaining methods

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(); 

所以当我调用$a->getRealValue(30)它应该返回30,

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

谢谢

所以当我调用$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"

这不是真的,$a->getRealValue(30)将返回对象$a不是值。但是asString将返回字符串格式的值。

通常当你想要得到这样的东西时,你可以这样做:

$a->getRealValue(30)->get();
//Or
$a->getRealValue(30)->getAsString();