Search code examples
phptype-conversionmagic-methods

PHP magic method __toNumber() converting object to number


Is there any way to implement a conversion of an object to a number in PHP?

There is a handy magic functon __toString() that can convert an object to string but how about object conversion to a number?

Example utilization:

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

that code generates the PHP notice (PHP 7.3)

Object of class Foo could not be converted to number

the list of PHP's magic methods does not have any __toNumber() method but perhaps there is a workaround to that? Obviously other than just using getter like:

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

Do you have any idea?


Solution

  • A comment was posted with the solution before I could finish my answer, but using __invoke() is the closest you can get:

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