How can a function be executed directly upon instantiating an object in PHP without the need for a separate code line like $obj->fn()?
To execute a function directly upon instantiating an object in PHP without the need for a separate code line, you can utilize the constructor method (__construct) in the class. By defining the desired function within the constructor, it will be automatically executed when an object is created. This allows you to perform actions immediately upon object instantiation without the need for an additional method call.
class MyClass {
public function __construct() {
$this->myFunction();
}
public function myFunction() {
echo "Function executed upon object instantiation.";
}
}
$obj = new MyClass(); // Output: Function executed upon object instantiation.
Related Questions
- What are the benefits of incorporating a unique, incrementing identifier like a report number in CSV data generated from PHP forms?
- How can the use of arrays in PHP improve the efficiency and functionality of the provided script for managing book database entries?
- What are the benefits of using DOMXpath in PHP when working with HTML elements like links?