Ensuring MySQL connection works in PHP function

别说谁变了你拦得住时间么 提交于 2019-12-31 01:57:08

问题


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();
?>

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?

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


回答1:


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


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


来源:https://stackoverflow.com/questions/394113/ensuring-mysql-connection-works-in-php-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!