Resolving "Cannot redeclare class" Errors in PHP
When you attempt to instantiate a class defined in a separate file, PHP's autoloading mechanisms or your manual include/require statements must be orchestrated correctly. The specific error you are encounteringâFatal error: Cannot redeclare class IUartsâis a classic symptom of namespace pollution or duplicate initialization logic within the same request lifecycle.
In your example, you are likely executing class.php directly in a browser (perhaps via php artisan tinker or by accessing the file as a URL). If page.php subsequently tries to include class.php, PHP sees that the class IUarts has already been defined and instantiated during the first load. Since PHP does not support redefining classes on the fly within the same execution context, it throws this fatal error immediately.
To use $vars = new IUarts(); in page.php without triggering a crash, you need to ensure that the class definition exists exactly once per request. The standard solution involves separating your logic into two distinct categories: definitions and instantiations.
Separating Definitions from Instantiation
Your current class.php file mixes two responsibilities: defining the class structure and instantiating it via the constructor. While constructors run automatically upon instantiation, the act of loading the file triggers the class definition itself.
If you access class.php directly, PHP defines IUarts. If you then navigate to or include page.php, which includes class.php again, the definition attempt fails.
The fix is to modify class.php so it only contains the class definition, not any automatic instantiation logic that might run if the file is loaded independently. More importantly, ensure that page.php does not accidentally trigger a double-load.
Here is how class.php should look:
<?php
namespace App\Models; // Optional but recommended for scalability
class IUarts {
public $data;
public function __construct() {
// Ensure get_data is available in your environment
if (function_exists('get_data')) {
$this->data = get_data('mydata');
} else {
throw new Exception('Helper function get_data not found.');
}
}
}
Notice the removal of any code that attempts to create an object inside the file. The file should be a blueprint, not a factory.
Correctly Loading the File in page.php
Now, looking at page.php, you must ensure that class.php is included only once. If your application architecture involves multiple entry points (e.g., a CLI script accessing both files, or a web server serving both), you need a guard to prevent duplicate includes.
The most robust pattern is to use a conditional check before including the file:
<?php
// page.php
if (!class_exists('IUarts', false)) {
// The 'false' flag ensures we don't return true if the class exists
// but was defined in a different namespace or context.
require_once LIB . '/class.php';
}
$vars = new IUarts();
print $vars->data;
This class_exists check acts as a safety net. If page.php is accessed directly, it loads the class. If page.php is included by another script that has already loaded class.php, the guard prevents the fatal error.
The Role of Autoloaders and Namespaces
While the manual include method works for simple scripts, larger applications often rely on autoloading standards like PSR-4. In a framework context (such as Laravel), you would rarely manually require files. Instead, you would define IUarts in your namespace structure and let the autoloader resolve it.
If you are moving towards a more scalable architecture, consider extracting get_data('mydata') into a dedicated service or repository class. Keeping dependencies like get_data tightly coupled within a constructor can make testing difficult. Refactoring to dependency injection would allow you to mock that helper function later without changing your core logic.
Common Pitfalls to Avoid
- Direct File Access: Never rely on accessing
.phpfiles directly via a web browser unless they are specifically designed as entry points (likeindex.php). Always route requests through your main application entry file, which handles the includes and autoloading logic centrally. - Ignoring Namespaces: If you define classes without namespaces in multiple locations, you risk colliding with global scope classes or other libraries. Using a namespace like
App\ServicesorMyProject\Modelsensures uniqueness across your project. - Re-running Constructors: Be aware that if you instantiate an object inside the constructor (as seen in your original code), and then try to serialize that object, the constructor might run again during deserialization depending on how it's handled. While not strictly related to the redeclaration error, it is a common source of infinite recursion bugs.
By treating class.php purely as a definition file and guarding its inclusion in page.php, you eliminate the "Cannot redeclare class" error and establish a cleaner separation of concerns.
