What are the best practices for controlling the frequency of including class definitions in PHP scripts?

To control the frequency of including class definitions in PHP scripts, it is best practice to use autoloading mechanisms such as PSR-4 standard autoloading. This allows classes to be automatically loaded only when they are needed, reducing the number of includes and improving performance.

// Implementing PSR-4 autoloading
spl_autoload_register(function ($class) {
    // Define the base directory for the namespace prefix
    $base_dir = __DIR__ . '/src/';

    // Remove the namespace prefix and replace namespace separators with directory separators
    $file = $base_dir . str_replace('\\', '/', $class) . '.php';

    // If the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});