How can methods from one class be accessed in another class in PHP, particularly when dealing with database operations?
To access methods from one class in another class in PHP, particularly when dealing with database operations, you can use inheritance or create an instance of the class containing the methods you want to access. By extending the class or creating an object of the class, you can then call the methods within the new class.
// Define a class with database operations
class Database {
public function fetchData() {
// Database operation logic
}
}
// Create a new class that extends the Database class
class DataProcessor extends Database {
public function processData() {
// Access fetchData method from Database class
$data = $this->fetchData();
// Process data logic
}
}
// Create an object of the DataProcessor class
$dataProcessor = new DataProcessor();
$dataProcessor->processData();
Keywords
Related Questions
- How can regular expressions be effectively used to extract specific information from a string in PHP?
- How can AJAX be used to dynamically load content in PHP to prevent interruptions in a web-based slideshow?
- How can database management and frame structures be utilized in PHP to enhance the synchronization of game actions between players in an online multiplayer game?