How can unexpected behavior be prevented when using dynamic class calls in PHP?

When using dynamic class calls in PHP, unexpected behavior can be prevented by checking if the class exists before attempting to instantiate it. This can be done using the class_exists() function to ensure that the class being called actually exists in the codebase.

if (class_exists($className)) {
    $object = new $className();
    // Rest of the code to work with the instantiated object
} else {
    // Handle the case where the class does not exist
    echo "Class $className does not exist";
}