What are the potential pitfalls of instantiating objects of one class within another class in PHP?

The potential pitfall of instantiating objects of one class within another class in PHP is tight coupling between the classes, making the code harder to maintain and test. To solve this issue, you can use dependency injection to pass the object as a parameter to the constructor of the class that needs it.

class ClassA {
    private $classB;

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

    public function doSomething() {
        // Use $this->classB here
    }
}

class ClassB {
    // ClassB implementation
}

$classB = new ClassB();
$classA = new ClassA($classB);
$classA->doSomething();