What are best practices for structuring PHP code to avoid the use of global variables, which can lead to confusion and errors?

Using global variables in PHP can lead to confusion and errors because they can be accessed and modified from anywhere in the code, making it difficult to track their values and causing unexpected behavior. To avoid this, it's best to encapsulate variables within classes or functions, using parameters and return values to pass data between different parts of the code.

class Example {
    private $data;

    public function setData($value) {
        $this->data = $value;
    }

    public function getData() {
        return $this->data;
    }
}

$example = new Example();
$example->setData('Hello, world!');
echo $example->getData();