How does hardcoding paths in PHP classes affect OOP principles and reusability?
Hardcoding paths in PHP classes violates the principle of encapsulation in object-oriented programming (OOP) and reduces reusability. To solve this issue, paths should be passed as parameters to the class constructor or methods, allowing for greater flexibility and easier reuse of the class in different contexts.
class FileHandler {
private $filePath;
public function __construct($filePath) {
$this->filePath = $filePath;
}
public function readFile() {
// Read file using $this->filePath
}
public function writeFile($data) {
// Write data to file using $this->filePath
}
}
// Example usage
$handler = new FileHandler('/path/to/file.txt');
$handler->readFile();
$handler->writeFile('Hello, World!');