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

有没有办法在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)


Foo 类的对象无法转换为数字


在PHP的魔术方法列表没有任何__toNumber()方法,但也许有一个解决方法是什么?显然,除了使用 getter 之外,例如:


getFactor() : float

{

     return $this->factor;

}

你有什么主意吗?


神不在的星期二
浏览 274回答 2
2回答

手掌心

在我完成我的回答之前,已经发布了带有解决方案的评论,但使用__invoke()是您可以获得的最接近的:<?phpclass Foo{&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* @var float&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; private $factor;&nbsp; &nbsp; public function __construct(float $factor)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->factor = $factor;&nbsp; &nbsp; }&nbsp; &nbsp; public function __invoke()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $this->factor;&nbsp; &nbsp; }}$foo = new Foo(1.23);$boo = 2;$result = $foo() * $boo;//wanted output 2.46echo $result;

DIEA

我想出的另一个解决方法是:<?phpclass Foo{&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* @var float&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; private $factor;&nbsp; &nbsp; public function __construct(float $factor)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->factor = $factor;&nbsp; &nbsp; }&nbsp; &nbsp; public function __toString()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return (string) $this->factor;&nbsp; &nbsp; }}$foo = new Foo(1.23);$boo = 2;$result = (string) $foo * $boo;//wanted output 2.46echo $result;echo " ";//doubleecho gettype($result);使用起来看起来非常不直观,但会产生想要的结果。
打开App,查看更多内容
随时随地看视频慕课网APP