What are the potential pitfalls of trying to call a function from an array of class instances in PHP?

When trying to call a function from an array of class instances in PHP, a potential pitfall is that not all instances may have the function defined, leading to errors. To solve this issue, you can use the method_exists() function to check if the function exists before calling it on each instance.

<?php

class MyClass {
    public function myFunction() {
        echo "Function called";
    }
}

$instance1 = new MyClass();
$instance2 = new MyClass();

$instances = [$instance1, $instance2];

foreach ($instances as $instance) {
    if (method_exists($instance, 'myFunction')) {
        $instance->myFunction();
    }
}

?>