[英]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.