What are the best practices for validating and restricting dynamic class calls in PHP?

When dynamically calling classes in PHP, it is important to validate and restrict the input to prevent potential security vulnerabilities such as code injection. One way to do this is by maintaining a whitelist of allowed classes and only allowing calls to those classes. This can be achieved by using a conditional statement to check if the requested class is in the whitelist before instantiating it.

// Define a whitelist of allowed classes
$allowedClasses = ['Class1', 'Class2', 'Class3'];

// Get the requested class name from user input
$requestedClass = $_GET['class'];

// Validate the requested class against the whitelist
if (in_array($requestedClass, $allowedClasses)) {
    // Instantiate the requested class
    $classInstance = new $requestedClass();
} else {
    // Handle invalid class request
    echo "Invalid class request";
}