我不确定如何命名,但我已经在 C# 中看到过类似的东西:
decimal value = 12.01;
print obj->getAmount() // 1002.01
print obj->getAmount()->format('...'); // 1.002,01
所以,在PHP上,我尝试了类似的东西:
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, ',', '.');
}
}
在可能的情况下,可以通过两种方式获取值:
$account->getAmount() // 1002.01
$account->getAmount()->format() // 1.002,01
但是,如果这可能的话,我会说缺少一些东西,我不确定该怎么做。
PHP 不能将对象转换为浮点数或整数,只能转换为字符串。这可用于显示目的:
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
但不要尝试对此做任何其他事情:
echo $account->getAmount() + 42; // 'Object of class Decimal could not be converted to int'
在帐户类中,您需要宣布$ammount变量删除变量名称中的下划线
并且您需要在创建其方法之前创建对象。