How can variables be passed to classes in PHP without using global variables?

When passing variables to classes in PHP without using global variables, you can utilize constructor injection. This involves passing the variables as arguments to the class constructor when creating an instance of the class. By doing so, you can ensure that the class has access to the necessary variables without relying on global scope.

<?php

// Define a class that accepts variables through constructor injection
class MyClass {
    private $variable;

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

    public function getVariable() {
        return $this->variable;
    }
}

// Create an instance of the class and pass the variable
$myVariable = "Hello, World!";
$myClass = new MyClass($myVariable);

// Access the variable within the class
echo $myClass->getVariable(); // Output: Hello, World!

?>