PHP 魔术方法 __toNumber() 将对象转换为数字

PHP magic method __toNumber() converting object to number

在PHP中有什么方法可以实现对象到数字的转换吗?

有一个方便的魔术函数 __toString() 可以将对象转换为字符串,但是如何将对象转换为数字呢?

使用示例:

<?php

class Foo
{
    /**
     * @var float
     */
    private $factor;

    public function __construct(float $factor)
    {
        $this->factor = $factor;
    }
}

$foo = new Foo(1.23);
$boo = 2;

$result = $foo*$boo;

//wanted output 2.46
echo $result;

该代码生成 PHP 通知 (PHP 7.3)

Object of class Foo could not be converted to number

list of PHP's magic methods 没有任何 __toNumber() 方法,但也许有解决方法? 显然除了使用 getter 之外:

getFactor() : float
{
     return $this->factor;
}

你有什么想法吗?

在我完成我的回答之前,有人对解决方案发表了评论,但使用 __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;

Demo

我想到的另一个解决方法是:

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

使用起来看起来非常不直观,但会产生想要的结果。