PHP global in functions

后端 未结 7 1184
梦谈多话
梦谈多话 2020-11-21 05:41

What is the utility of the global keyword?

Are there any reasons to prefer one method to another?

  • Security?
  • Performance?
  • Anything els
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 06:00

    Simply put there is rarely a reason to global and never a good one in modern PHP code IMHO. Especially if you're using PHP 5. And extra specially if you're develop Object Orientated code.

    Globals negatively affect maintainability, readability and testability of code. Many uses of global can and should be replaced with Dependency Injection or simply passing the global object as a parameter.

    function getCustomer($db, $id) {
        $row = $db->fetchRow('SELECT * FROM customer WHERE id = '.$db->quote($id));
        return $row;
    }
    

提交回复
热议问题