PHP函数的范围 [英] Scope of PHP function
问题描述
我有一个文件将我的可重用函数集成到一个文件中( functions.php
)。它在每个需要它的页面上都是 include_once()
'd。当我的自定义函数试图访问自己范围之外的MySQL连接时,出现错误。源代码有点像这样:
<?php
// functions.php
$ connect = mysql_connect(localhost,user,pass)或死(MySQL说:.mysql_error());
mysql_select_db(database,$ connect)或死(MySQL说:.mysql_error()); //没有错误
/ * ... * /
函数getmotd($ user){
$ query =SELECT cid FROM`users`
WHERE id =。$ user;
$ query = mysql_query($ query,$ connect); //错误发生在这里,$ connect不是一个有效的MySQL链接资源
/ * ... * /
}
?>
为什么我的函数访问变量不能在其范围之上声明?我可以通过在函数中复制 $ connect
的声明来获得成功的连接。
使用 global
关键字。
示例
函数getmotd($ user){
global $连接;
$ query =SELECT cid FROM`users`
WHERE id =。$ user;
$ query = mysql_query($ query,$ connect); //错误发生在这里,$ connect不是有效的MySQL链接资源
/ * ... * /
}
你也可以这样做
函数getmotd($ user){
$ query =SELECT cid FROM`users`
WHERE id =。$ user;
$ query = mysql_query($ query,$ GLOBALS ['connect']); //错误发生在这里,$ connect不是有效的MySQL链接资源
/ * ... * /
}
如果您想制作可重复使用的代码,那么使用OOP可能会更好。为数据库创建一个类,然后为数据库信息添加一些属性,并使用 this
关键字从函数中访问它们。
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 an error when my custom functions are trying to access a MySQL connection outside their own scope. The source is a bit like this:
<?php
// functions.php
$connect = mysql_connect("localhost", "user", "pass") or die("MySQL said: ".mysql_error());
mysql_select_db("database", $connect) or die("MySQL said: ".mysql_error()); // no error
/* ... */
function getmotd($user) {
$query = "SELECT cid FROM `users`
WHERE id = ".$user;
$query = mysql_query($query, $connect); // error occurs here, $connect is not a valid MySQL link-resource
/* ... */
}
?>
Why can't my function access variables declared above it's scope? I can get a successful connection by reproducing $connect
's declaration within the function.
Any insight into how I can work around this or what I'm doing wrong here?
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.
这篇关于PHP函数的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!