我应该继续在PHP中重新连接到mysql吗? [英] Should I keep reconnecting to mysql in PHP?

查看:103
本文介绍了我应该继续在PHP中重新连接到mysql吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的站点,每个页面都是由几个包含的文件构建的,我的站点是过程格式的100%,我正在尝试学习在PHP中使用类和更多的OOP方法.

I have a pretty large site and every page is built from several included files, my site is 100% in a procedural format and I am trying to learn to use classes and a more OOP approach in PHP.

当前,我的站点的头文件包含在每个页面中,该头是建立的mysql连接,持续到页面持续时间,因此,如果我需要从不同的文件运行10个不同的查询,则它们无需建立新连接即可运行,因此连接仅建立一次.

Currently my site has a header file that is included into every page, in this header is a mysql connection that is made and last the duration of the page, so if I need to run 10 different queries from different files, they all run without needing to make a new connection, so the connection is only made once.

现在,我正尝试转换为更多的OO方式,我首先要编写一个mysql类来连接和运行查询,所以我正在考虑使用__construct类来建立与mysql的连接,我只是奇怪的是,每次调用该类时,它将建立或尝试建立与mysql的连接,而不仅仅是一次.

Now that I am trying to convert to a more OO way, I am starting with writing a mysql class to connect and run queries, so I am thinking of using the classes __construct function to make a connection to mysql, I am just curious how this would work though, everytime that class gets called it would make or try to make a connection to mysql instead of just once.

也许我没有清楚地考虑.我应该只在标题中启动该类1次,然后再不必担心吗?

Maybe I am not thinking it out clearly. Should I just initiate this class in the header 1 time and then I wont have to worry anymore?

推荐答案

您可以创建MySQL类的单个全局对象,并在任何地方使用该对象.然后,您的构造函数将只被调用一次.

You could create a single global object of your MySQL class and use that object everywhere. Then your constructor would only be called once.

或者您可以在任何地方创建MySQL类的新对象.如果已经打开一个 mysql_connect 不会打开新连接:

Or you could create new objects of your MySQL class everywhere. mysql_connect doesn't open new connections if there already is one open:

如果使用相同的参数再次调用mysql_connect(),则不会建立新的链接,而是将返回已打开的链接的链接标识符.

If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

这篇关于我应该继续在PHP中重新连接到mysql吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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