Is there any other way instead of using global everytime I need to access a global variable inside a function?
$db = new ezSQL_mysql("root", "", "payroll", "localhost");
class employee{
function get_emp(){
global $db;
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In normal global-scope functions, either use the
globalkeyword, or$GLOBALS['db']superglobal array (which is preferable for readability). The other alternative is to pass the global variable into the function as a parameter.In your class, the best method is dependency injection. Your class constructor receives the
$dbas a parameter, which makes it available to all class methods: