Fixing reports of undefined methods
Last updated on
7 January 2022
This documentation needs work. See "Help improve this page" in the sidebar.
When working with entities, often times PHPStan only knows the object as EntityInterface and not the actual entity. In your code, whenever working with an entity, make sure to type hint using one of the following ways:
// Using asserts – great for development, as it'll throw an error at runtime if wrong (ie: null or wrong object type.)
$foo = $node->get('some_entity_reference')->entity;
assert($foo instanceof \Drupal\taxonomy_term\TermInterface);
// Use doc type hinting.
/** @var \Drupal\taxonomy_term\TermInterface $foo */
$foo = $node->get('some_entity_reference')->entity;
// Put your code in an if statement
$foo = $node->get('some_entity_reference')->entity;
if ($foo instanceof \Drupal\taxonomy_term\TermInterface) {
}
If you are working with hooks, just update the parameter type hint.
mymodule_node_insert(NodeInterface $node)Help improve this page
Page status: Needs work
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.