How to pass Global variables to classes in PHP?

后端 未结 5 1546
终归单人心
终归单人心 2021-01-05 02:41

How can I pass the global variables to the classes I want to use without declare them as GLOBAL in every method of the class ?

example :

$admin = \"         


        
5条回答
  •  一整个雨季
    2021-01-05 03:09

    Well, you can declare a member variable, and pass it to the constructor:

    class Administrator {
        protected $admin = '';
    
        public function __construct($admin) {
            $this->admin = $admin;
        }
    
        public function logout() {
            $this->admin; //That's how you access it
        }
    }
    

    Then instantiate by:

    $adminObject = new Administrator($admin);
    

    But I'd suggest trying to avoid the global variables as much as possible. They will make your code much harder to read and debug. By doing something like above (passing it to the constructor of a class), you improve it greatly...

提交回复
热议问题