The project I am working on is full of statements like global $app;
. Is there any way to use $app
directly without global $app;
?
The project I am working on is full of statements like global $app;
. Is there any way to use $app
directly without global $app;
?
Regardless of OOP, variables outside functions in PHP are global variables.
To use global variables within a function, you need to use global declarations. Of course, you can also consider passing parameters.
PHP itself provides many "super" Global variables such as $_SERVER/$_COOKIE, etc. do not require a global declaration.
Windows registry appears to PHPer as a $win = array();
Hash table (multi-dimensional array) in the global scope, which can store various Configuration information of various applications and modules. Why does PHP web application exclude such an application-level global array? Like Discuz!, there is such a global array named $_G[].
Of course, some people are uncomfortable with OOP and just don’t like global arrays, so that’s fine:
<code><?php class App { private static $options = array( 'db_host' => '127.0.0.1', 'db_user' => 'yaber', 'db_pass' => '123456', 'db_name' => 'yabase', 'db_port' => 3306 ); public static function config($key = '') { return ($key == '') ? self::$options : self::$options[$key]; } } function bar() { echo App::config('db_name'); } bar(); //输出 yabase</code>
The biggest advantage of static methods of a class is that the class can be directly used without instantiation, but it cannot access the non-static member variables and methods of the class.