2 回答

TA貢獻1942條經驗 獲得超3個贊
在我完成我的回答之前,已經發布了帶有解決方案的評論,但使用__invoke()是您可以獲得的最接近的:
<?php
class Foo
{
/**
* @var float
*/
private $factor;
public function __construct(float $factor)
{
$this->factor = $factor;
}
public function __invoke()
{
return $this->factor;
}
}
$foo = new Foo(1.23);
$boo = 2;
$result = $foo() * $boo;
//wanted output 2.46
echo $result;

TA貢獻1820條經驗 獲得超2個贊
我想出的另一個解決方法是:
<?php
class Foo
{
/**
* @var float
*/
private $factor;
public function __construct(float $factor)
{
$this->factor = $factor;
}
public function __toString()
{
return (string) $this->factor;
}
}
$foo = new Foo(1.23);
$boo = 2;
$result = (string) $foo * $boo;
//wanted output 2.46
echo $result;
echo " ";
//double
echo gettype($result);
使用起來看起來非常不直觀,但會產生想要的結果。
- 2 回答
- 0 關注
- 295 瀏覽
添加回答
舉報