How can an instance of a class be created within another class in PHP?
To create an instance of a class within another class in PHP, you can simply instantiate the class within the constructor or a method of the outer class. This allows you to access the properties and methods of the inner class within the outer class.
class InnerClass {
public function __construct() {
echo "Inner class instance created";
}
}
class OuterClass {
public $innerInstance;
public function __construct() {
$this->innerInstance = new InnerClass();
}
}
$outer = new OuterClass();
Related Questions
- Are there any specific considerations or steps to take when installing PHP on a personal Apache server?
- What are the best practices for rounding time values in PHP, especially when dealing with time tracking or recording functionalities?
- What are the best practices for handling and storing extracted data from webpages in a PHP application?