Can a certain class be expanded globally in php?

WBOY
Release: 2016-09-14 09:41:26
Original
1158 people have browsed it

The project I am working on is full of statements like global $app;. Is there any way to use $app directly without global $app;?

Reply content:

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>
Copy after login

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.

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template