dtdfl62844 2013-07-25 10:40
浏览 64

在函数中使用数据库对象

In a webapp I am building I make use of a PDO database object for querying my database. This is instantiated at the top of every page using a custom class that I built based on PDO:

$db = new database; //database is the name of my class.

I then use the class like so in my script:

$db->query("SELECT field FROM table");
$results = $db->resultset();

I have a number of standalone functions that need to make use of the database object.

My question is is it better practise to pass the $db to the function as an argument or just globalize from within the function, given $db is a globally used variable. However I have heard things about avoiding polluting the global namespace.

i.e.

function myFunction($db, $a1, $a2){
    //stuff
}

vs

function myFunction($a1, $a2){
    global $db;
    //stuff
}
  • 写回答

1条回答 默认 最新

  • dongmei8460 2013-07-25 10:45
    关注

    In my opinion, global vars are rarely a good practice. I think you should use the first solution: passing the db instance as first parameters to your function.

    IF you only have one instance of your database, an even better option would be to make your database class a singleton. This would allow you to do something like $db = database.getInstance(); in your functions.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题