Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(php) Better way to use global variables? Or how to avoid them?

Tags:

oop

php

global

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...

like image 989
Martin Zeltin Avatar asked Oct 15 '25 03:10

Martin Zeltin


1 Answers

Generally speaking, global variables are not good. There are some methods to avoid global variables.

Use a base class

class Base 
{
    protected $db, $config;
}

class Layout extends Base 
{
    public void foo() 
    {
        $this->db->query(...);
    }
}

Use namespace

namespace MyProject
{
    function DB()
    {
        ....
    }
}

class Layout
{
    public void foo() 
    {
        \MyProject\DB()->query(...);
    }
}

Use some frameworks, like Symfony, Laravel, etc (also you can consider some ORM-only frameworks)

The famous frameworks do good job.

  • Symphony: https://symfony.com/doc/current/doctrine.html
  • Laravel: https://laravel.com/docs/5.6/database

  • ORM concept: What is an Object-Relational Mapping Framework?

like image 174
shawn Avatar answered Oct 17 '25 23:10

shawn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!