Coder-Spirit / php-bignumbers

A robust library to handle immutable big numbers inside PHP applications
MIT License
131 stars 29 forks source link

Constructors using self #35

Closed josecelano closed 9 years ago

josecelano commented 9 years ago

I am trying to extend Decimal class to add some methods like greaterThan, ...

It would be easier for me if you use self in constructor.

Constructor from integer:

    /**
     * @param  integer $intValue
     * @return Decimal
     */
    public static function fromInteger($intValue)
    {
        ....
        return new Decimal((string)$intValue, 0);
    }

Extended class example:

class ExtrendedDecimal
{
    /**
     * @param  Decimal $b
     * @param  integer $scale
     * @return bool
     */
    public function greaterThan(Decimal $b, $scale = null)
    {
        if ($this->comp($b, $scale) == 1)
            return true;
        else
            return false;
    }
}

New using Self:

return new Self((string)$intValue, 0);

I know that is not a great new feature but I want to use my own class in case I need some extensions in the future.

castarco commented 9 years ago

Solved, thanks for the idea.

castarco commented 9 years ago

By the way, I'm interested on how people use this library. I'm very biased to theoretical approaches and usages, and the next refactorization that I want to apply will go in this direction. What are the features most used by you? What do you think this library needs?

josecelano commented 9 years ago

Sorry, It does not work. This is the rigth way:

return new static((string)$intValue, 0);

self returns always your base clase (Decimal). With static your code would return the extended class. More info: http://php.net/manual/en/language.oop5.late-static-bindings.php

I am using the library to implement a new version of this library: https://github.com/mathiasverraes/money whithout the max integer limit for 32 bits systems. This is my fork using your class instead of int: https://github.com/josecelano/money Here there is another library which uses BCMath library directly: https://github.com/keiosweb/moneyright