The short answer is: no. There isn't a way to change the way scope is handled in PHP.
Since that's probably not very helpful to you, I'll try to explain a better approach.
The global
keyword is one of PHP's idiosyncrasies. Some people think it's dumb, but there's a certain logic to it. Lots of patterns in programming are about keeping dependencies explicit. Stuff that happens inside your class shouldn't depend on the state of the world outside. In your case (or whenever you import a global variable using global
, you're coupling your class to the environment it lives in. This is bad for various reasons.
If your class requires a database connection, you should be injecting the dependency explicitly, not implicitly pulling it from global scope.
If the dependency is required for the class to function, the obvious place to inject it is in the constructor.
For example:
<?php
class MyComponent
{
/**
* @param mysqli $mysqli
*/
public function __construct($mysqli)
{
$this->mysqli = $mysqli;
}
public function getBars()
{
$bars = $this->mysqli->query('...');
return $bars;
}
}
// now back in the global scope
$mysqli = mysqli_connect('localhost', 'joe', 'secret', 'foodb');
$component = new MyComponent($mysqli);
$bars = $component->getBars();