PHP:无法访问$ DB变量函数的范围
问题描述:
我创建了一个功能来检查记录存在与否,但它给了我这些错误:
注意:未定义的变量:DB在d: \ wamp \ www \ Whq \ admin_operation.php on line 31
致命错误:调用第31行的D:\ wamp \ www \ Whq \ admin_operation.php中的非对象的成员函数query()
if($mode=='add_image')
{ $tags_array = array();
$tags = $_POST['tags'];
/*function to check tag exist or not */
function check_tag_exist($t)
{
$result = $db->query('select tag_name from whq_tags where tag_name like "'.$t.'" ');
$no=$result->num_rows;
if($no==0)
{
return true;
}
else
{
return false;
}
}
/* prepared stmnt created for whq_tags table */
if($stmt = $db->prepare('insert into whq_tags(tag_name) values (?)'))
{
$stmt -> bind_param('s', $tags_name);
foreach($tags as $tag1)
{
$tag1 = $tags_name;
if(check_tag_exist($tags_name))
{
$db->execute();
}
}
/* Close the statement */
$stmt->close();
}
else
{
/* Error */
printf("Prepared Statement Error: %s\n", $db->error);
}
}
变量$ db里面check_tag_exist函数不工作,而它在其他地方工作。请帮助我。 在此先感谢。
答
由于变量的作用域,变量在您的函数中无法访问。从PHP文档阅读variable scope。
可以传递$ DB变量到函数作为参数:
function check_tag_exist($t, $db) { ... }
$ DB变量在该函数范围。 – 2014-10-19 06:47:12
您在可见度方面存在问题。在函数外部定义的变量在函数内部是不可见的,除非您将它们作为参数传递或将其声明为全局变量。 – 2014-10-19 06:48:07
这是一个可变范围问题 - http://php.net/manual/en/language.variables.scope.php。添加'$ db'到函数params - >'function check_tag_exist($ t,$ db)' – Sean 2014-10-19 06:48:20