How to use $GLOBALS in PHP MVC framework

look directly at the code on the Internet (code is correct):

but this code is to be put into the mvc framework and how it should be used. I wrote the following code (take the ci framework as an example):

class Welcome extends CI_Controller
{
    public $name = "TOM";
    public function index()
    {
        echo "myname is " . $GLOBALS["name"] . "<br>";
    }
}

:Undefined index: name

mvc$GLOBALS
Php
Mar.16,2021

I also encountered related problems when using CI, that is, CodeIgniter development, but I did not use global variables to solve them, and I personally do not advocate the use of global variables in the MVC framework. Global variables are easy to be accessed and modified by various parts of the code, resulting in too much uncertainty, and variables are generally encapsulated in classes and should not be accessed outside the class

1. Write the global variables you need into config.php as configuration variables

$config['name']= 'TOM';

2, when the variable needs to be referenced

$name = $this->config->item('name');
echo $name;
// Tom

the above method refers to the configuration class of CI. This method is easy to use and works globally, but the disadvantage is that if you need to set a lot of variables, or read variables from the database, then this method will not work

Menu