1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-05 21:19:03 +01:00
psalm/docs/running_psalm/issues/MixedMethodCall.md

67 lines
1.1 KiB
Markdown
Raw Normal View History

2020-03-19 17:32:49 +01:00
# MixedMethodCall
Emitted when calling a method on a value that Psalm cannot infer a type for
```php
2020-03-21 00:13:46 +01:00
<?php
2020-03-21 22:33:37 +01:00
class A {
public function foo() : void {}
2020-03-19 17:32:49 +01:00
}
2020-03-21 22:33:37 +01:00
function callFoo(array $arr) : void {
array_pop($arr)->foo(); // MixedMethodCall emitted here
}
callFoo(
[new A()]
);
```
## Why this is bad
If Psalm does not know what `array_pop($arr)` is, it can't verify whether `array_pop($arr)->foo()` will work or not.
2020-03-21 22:33:37 +01:00
## How to fix
Make sure that to provide as much type information as possible to Psalm so that it can perform inference. For example, you could add a docblock to the `callFoo` function:
```php
<?php
class A {
public function foo() : void {}
}
/**
* @param array<A> $arr
*/
function callFoo(array $arr) : void {
array_pop($arr)->foo(); // MixedMethodCall emitted here
}
callFoo(
[new A()]
);
```
Alternatively you could add a runtime check:
```php
<?php
class A {
public function foo() : void {}
}
function callFoo(array $arr) : void {
$a = array_pop($arr);
assert($a instanceof A);
$a->foo(); // MixedMethodCall emitted here
}
callFoo(
[new A()]
);
2020-03-19 17:32:49 +01:00
```