Sobes.tech
Junior — Middle

How to perform automatic initialization of class B object during the creation of class A object?

sobes.tech AI

Answer from AI

To automatically initialize an object of class B when creating an object of class A in PHP, the constructor of class A is usually used, in which an instance of class B is created and stored in a property.

Example:

class B {
    public function __construct() {
        // Initialization of B
    }
}

class A {
    private $b;

    public function __construct() {
        $this->b = new B(); // Automatic initialization of B
    }

    public function getB() {
        return $this->b;
    }
}

$a = new A();
$b = $a->getB();

Thus, when creating an object of class A, an object of class B is automatically created and accessible through a property or method of class A.