How can passing arrays through constructors or using setter methods improve code quality and reduce the reliance on global variables in PHP?

Passing arrays through constructors or using setter methods allows for better encapsulation and reduces the reliance on global variables in PHP. By passing arrays as parameters to constructors or using setter methods, you can ensure that the necessary data is provided to the object without needing to access global variables. This approach also makes the code more modular and easier to test.

class User {
    private $userData;

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

    public function setUserData(array $userData) {
        $this->userData = $userData;
    }

    public function getUserData() {
        return $this->userData;
    }
}

$userData = ['name' => 'John Doe', 'email' => 'john.doe@example.com'];
$user = new User($userData);

// Or using setter method
$newUserData = ['name' => 'Jane Smith', 'email' => 'jane.smith@example.com'];
$user->setUserData($newUserData);

var_dump($user->getUserData());