What are the different ways to use a class as a member variable in another class in PHP?

When using a class as a member variable in another class in PHP, you can instantiate the class directly within the constructor of the class that will contain it. Alternatively, you can pass an instance of the class as an argument to the constructor of the class that will contain it. This allows for composition and encapsulation of functionality within the classes.

<?php

// Example of using a class as a member variable in another class in PHP

class ClassA {
    public function methodA() {
        echo "Method A called from Class A\n";
    }
}

class ClassB {
    private $classA;

    public function __construct() {
        $this->classA = new ClassA();
    }

    public function methodB() {
        echo "Method B called from Class B\n";
        $this->classA->methodA();
    }
}

// Usage
$classB = new ClassB();
$classB->methodB();

?>