Skip to content

UnnecessaryCasting ​

info on by default quick-fix

Group: Code style · PhpStorm name: UnnecessaryCastingInspection

A type cast whose operand already has exactly the target type, or a string cast used as an operand of concatenation (which converts to string anyway), is noise. Dropping it simplifies the expression.

Example ​

php
<?php
$text  = 'abc';
$list  = [1];
$flag  = false;
$ratio = 1.5;
$count = 4;

return [
    (string) $text,
    (array) $list,
    (bool) $flag,
    (double) $ratio,
    (integer) ($count * 3),
    (float) ($count - 0.5),
    (int) ($count / 2),
    (float)-2.25,
    (int) ($count * 0.5),
    (int) ($count + $missing),
    (string) $missing,
];

function strictArg(int $n, $loose) {
    return [(int) $n, (int) $loose];
}

class Meter {
    /** @var int */
    private $hidden;
    /** @var int */
    public $shown;
    public function size(): int { return 1; }
    /** @return int */
    public function legacy() { return 1; }

    public function read(?Meter $other) {
        return [
            (int) $this->hidden,
            (int) $this->shown,
            (int) $this->size(),
            (int) $this->legacy(),
            (int) $other?->size(),
            (int) ($this->shown ?? 0),
        ];
    }
}

function joins(string $a, int $b, ?string $c, $d, \Stringable $e, string|false $f) {
    $a .= (string) $b;
    $a .= (string) $c . (string) $d . (string) $e . (string) $f . (string) true;
    return 'n=' . (string)$b . (string) 2.5;
}

function stamps() {
    return [
        (int) (microtime() * 10),
        (int) (microtime(true) * 10),
        (bool) end($GLOBALS),
    ];
}

Reported:

  • line 9: Operand already has the target type; remove the cast.
  • line 10: Operand already has the target type; remove the cast.
  • line 11: Operand already has the target type; remove the cast.
  • line 12: Operand already has the target type; remove the cast.
  • line 13: Operand already has the target type; remove the cast.
  • line 14: Operand already has the target type; remove the cast.
  • line 16: Operand already has the target type; remove the cast.
  • line 23: Operand already has the target type; remove the cast.
  • line 37: Operand already has the target type; remove the cast.
  • line 39: Operand already has the target type; remove the cast.
  • line 48: Concatenation converts to string anyway; remove the cast.
  • line 50: Concatenation converts to string anyway; remove the cast.
  • line 55: Operand already has the target type; remove the cast.

Configure ​

In custos.json:

json
{
  "rules": {
    "UnnecessaryCasting": {
      "enabled": false
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file), either of:

php
// @custos-ignore UnnecessaryCasting

/**
 * @noinspection UnnecessaryCastingInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.