In PHP, what are some alternative methods to using global variables within a class?

Using global variables within a class can lead to tight coupling and make the code harder to maintain and test. To avoid this, you can use dependency injection or pass the required variables as parameters to the class methods.

class MyClass {
    private $dependency;

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

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

// Usage
$dependency = new Dependency();
$myClass = new MyClass($dependency);
$myClass->doSomething();