Skip to content

Commit

Permalink
Add explanation for MixedMethodCall
Browse files Browse the repository at this point in the history
  • Loading branch information
muglug committed Mar 21, 2020
1 parent e6a0fe0 commit e557933
Showing 1 changed file with 57 additions and 3 deletions.
60 changes: 57 additions & 3 deletions docs/running_psalm/issues/MixedMethodCall.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,62 @@ Emitted when calling a method on a value that Psalm cannot infer a type for
```php
<?php

/** @param mixed $a */
function foo($a) : void {
$a->foo();
class A {
public function foo() : void {}
}

function callFoo(array $arr) : void {
array_pop($arr)->foo(); // MixedMethodCall emitted here
}

callFoo(
[new A()]
);
```

## Why this is bad

If Psalm doesn’t know what `array_pop($arr)` is, it can't verify whether `array_pop($arr)->foo()` will work or not.

## 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()]
);
```

0 comments on commit e557933

Please sign in to comment.