正确的 php 类型提示为学说列类型"decimal"



我在我的一个实体中使用此列:

/**
 * @var float
 * @ORMColumn(type="decimal", precision=20, scale=2)
 */
public $value;

根据学说文档,decimal类型作为string返回到PHP,但我将其用作float。我应该用 @var float键入它,还是 @var string正确?

无论如何,如果我将此变量用于算术计算,例如。

$object->value + $otherobject->value

我有可能获得不希望的行为(例如仅添加整数零件(?

使用Symfony 4提供的命令行工具生成实体,可以像这样生成类型decimal的字段:

New property name (press <return> to stop adding fields):
> percent
Field type (enter ? to see all types) [string]:
> decimal
Precision (total number of digits stored: 100.00 would be 5) [10]:
> 5
Scale (number of decimals to store: 100.00 would be 2) [0]:
> 4

这将导致以下属性和getter/setter方法:

<?php
// ...
/**
 * @ORMColumn(type="decimal", precision=5, scale=4)
 */
private $percent;
public function getPercent()
{
    return $this->percent;
}
public function setPercent($percent): self
{
    $this->percent = $percent;
    return $this;
}

因此,每个默认学说生成无类型提示的Getter/setter方法。
Getter将返回string,而Setter则期望类型double的参数(这只是float的同义词(。
因此,您无法做类似的事情:

/**
 * @var float
 */
private $value;

由于该值将作为字符串返回,因此您不应该像问题中的一个一样进行计算,而是要注意以前的转换。

编辑:
使用stringfloat提示的类型提示的替代方法可以是外部库PHP小数。

您可以使用此命令安装它:

composer require php-decimal/php-decimal

我会这样:

/**
 * @var float
 *
 * @ORMColumn(type="float", precision=20, scale=2)
 */
public $value;

最新更新