0

I'm not sure how name this but I have already seen in C# something like:

decimal value = 12.01;
print obj->getAmount() // 1002.01
print obj->getAmount()->format('...'); // 1.002,01

So, On PHP I tried something like:

class Account {
    public function getAmount() {
        return new Decimal($this->_amount);
    }
}

class Decimal {

    private $_value;

    public function __construct($value) {
        $this->_value = $value;
        return (float) $this->_value;
    }

    public function format() {
        return number_format($this->_value, 2, ',', '.');
    }

}

Where was possible get the value in two ways:

$account->getAmount() // 1002.01
$account->getAmount()->format() // 1.002,01

But, if this is possible I would say that something is missing and I'm not sure how to do.

Pablo
  • 1,953
  • 4
  • 28
  • 57

2 Answers2

1

PHP can't convert objects to floats or ints, only to strings. This can be used for display purposes:

class Account {

    public function __construct($amount) {
        $this->_amount = $amount;
    }
    public function getAmount() {
        return new Decimal($this->_amount);
    }
}

class Decimal {

    private $_value;

    public function __construct($value) {
        $this->_value = $value;
    }
    public function __toString() {
        return strval($this->_value);
    }
    public function format() {
        return number_format($this->_value, 2, ',', '.');
    }
}

$account = new Account(1002.01);

echo $account->getAmount(), "\n"; // 1002.01
echo $account->getAmount()->format(), "\n"; // 1.002,01

but don't attempt to do anything else with that:

echo $account->getAmount() + 42; // 'Object of class Decimal could not be converted to int'
georg
  • 211,518
  • 52
  • 313
  • 390
0

In Account class you need to announce $ammount variable Remove underscore in variable names

And you need to create object before creating its methods.

Tolma4
  • 1
  • 1