Scope of PHP function

前端 未结 2 1885
灰色年华
灰色年华 2021-01-19 09:41

I have a file that corrals my re-usable functions into one file (functions.php). It\'s include_once()\'d on every page that needs it. I\'m getting

2条回答
  •  -上瘾入骨i
    2021-01-19 10:21

    Use the global keyword.

    Example

    function getmotd($user) {  
         global $connect;
        $query = "SELECT cid FROM `users`
        WHERE id = ".$user;
        $query = mysql_query($query, $connect); // error occurs here, $connect is not a valid MySQL link-resource
        /* ... */
    }
    

    You can also do it like this

    function getmotd($user) {  
        $query = "SELECT cid FROM `users`
        WHERE id = ".$user;
        $query = mysql_query($query, $GLOBALS['connect']); // error occurs here, $connect is not a valid MySQL link-resource
        /* ... */
    }
    

    If you want to make re-usable codes, you'd probably be better off with OOP. Create a class for the database, and add some properties for the database info, and access them from the functions by using the this keyword.

提交回复
热议问题