确保MySQL连接在PHP函数中有效 [英] Ensuring MySQL connection works in PHP function

查看:76
本文介绍了确保MySQL连接在PHP函数中有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码具有以下形式:

I have code with the following form:

<?php
function doSomething{
  //Do stuff with MySQL
  $con->tralalala();
}
$con = connectToDatabase;//This would actually be a line or two.
doSomething();
?>

此(类型)代码不起作用,因为doSomething()没有与数据库的连接.谁能解释为什么不呢?我在调用doSomething()之前先创建$ con连接.那么,为什么该功能就像没有连接一样起作用?

This (type of) code doesn't work, because doSomething() doesn't have a connection to the database. Can anyone explain why not? I create the $con connection before I call doSomething(). So why does the function act as if there's no connection?

除了将连接传递到doSomething($ con)之类的函数之外,有什么方法可以解决此问题?

Is there any way to fix this, short of passing the connection into the function like doSomething($con)?

推荐答案

您可能需要告诉它在全局范围内查看:

you probably need to tell it to look in the global scope:


     function doSomething()
     {
         global $con;
         $con->tralalala();
     }

这篇关于确保MySQL连接在PHP函数中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆