What potential pitfalls should be avoided when trying to access external objects within a PHP class?
When accessing external objects within a PHP class, it's important to avoid tight coupling and maintain encapsulation. This means that the class should not directly instantiate or access external objects, but instead rely on dependency injection or interfaces to interact with them. This approach promotes better code organization, testability, and flexibility in the long run.
class MyClass {
private $externalObject;
public function __construct($externalObject) {
$this->externalObject = $externalObject;
}
public function doSomething() {
$this->externalObject->method();
}
}
$externalObject = new ExternalObject();
$myClass = new MyClass($externalObject);
$myClass->doSomething();