Scope of PHP function

前端 未结 2 1883
灰色年华
灰色年华 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条回答
  • 2021-01-19 10:02

    You can't access $connect because it is outside the scope of the function; that is, PHP can only see the variables within the function when it's inside it. You could use the global keyword to let PHP know the variable is outside the function's scope as Kemal suggests, but I think a better course of action is to pass the connection into the function. This will give you better encapsulation. If you learn to write your functions (and later classes) with passing in the resources and data you need (a practice known as "dependency injection"), you'll find you have cleaner and more maintainable code. Here's the example:

    function getmotd($db, $user) {
        $query = "SELECT cid FROM users WHERE id = " . (int)$user;
        $result = mysql_query($query, $db);
        /.../
    }
    
    $connect = mysql_connect(...);
    mysql_select_db(...);
    $motd = getmotd($connect, $user);
    

    Hope this helps.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题