How can objects in one class be used as attributes in another class in PHP?

To use objects in one class as attributes in another class in PHP, you can create an instance of the object in the class where you want to use it and then pass it as a parameter to the constructor of the other class. This allows you to access the methods and properties of the object within the second class.

class ClassA {
    public $attribute;

    public function __construct($attribute) {
        $this->attribute = $attribute;
    }
}

class ClassB {
    public $classA;

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

    public function useAttribute() {
        echo $this->classA->attribute;
    }
}

$objectA = new ClassA('Hello');
$objectB = new ClassB($objectA);
$objectB->useAttribute(); // Output: Hello