I was reading somewhere that using global variables is generally a bad idea but I am not sure what the alternative is...
I have this code now and I need to use global $config, $db
in every single function. = copy & paste
class Layout {
public static function render($file, $vars) {
global $config, $mysql_db;
mysqli_query($mysql_db, "SELECT * FROM users");
}
}
Is there a better way to do this or do I need to use global keyword or define globals? Because I will need things like mysql connection variables in every function...
Generally speaking, global variables are not good. There are some methods to avoid global variables.
class Base
{
protected $db, $config;
}
class Layout extends Base
{
public void foo()
{
$this->db->query(...);
}
}
namespace MyProject
{
function DB()
{
....
}
}
class Layout
{
public void foo()
{
\MyProject\DB()->query(...);
}
}
The famous frameworks do good job.
Laravel: https://laravel.com/docs/5.6/database
ORM concept: What is an Object-Relational Mapping Framework?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With