Error Identifier: clone.nonObject
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
$value = 'hello';
$cloned = clone $value;
Why is it reported? #
The clone keyword is applied to a value that is not an object. In PHP, only objects can be cloned. Attempting to clone a non-object value will result in a TypeError at runtime.
In the example above, a string is being cloned, which is not valid.
How to fix it #
Ensure the value being cloned is an object:
<?php declare(strict_types = 1);
-$value = 'hello';
+$value = new \stdClass();
$cloned = clone $value;
If the variable can hold both object and non-object types, narrow the type before cloning:
<?php declare(strict_types = 1);
function cloneIfObject(mixed $value): mixed
{
+ if (is_object($value)) {
+ return clone $value;
+ }
+
- return clone $value;
+ return $value;
}
How to ignore this error #
You can use the identifier clone.nonObject to ignore this error using a comment:
// @phpstan-ignore clone.nonObject
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: clone.nonObject