簡體   English   中英

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM