Scope of PHP function

前端 未结 2 1884
灰色年华
灰色年华 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.

提交回复
热议问题