PHP:让其他函数访问我的数据库连接函数中的 $conn 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32188985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP : Make other functions access the $conn variable inside my database connection function
提问by Asperger
Make other functions access the $conn variable inside my database connection function
使其他函数访问我的数据库连接函数中的 $conn 变量
So here I am absolutely desperate trying to make something work. I know what im trying to do is not OOP neither 100% best practice. It is not for a live website, I am just learning some basic PHP concepts on XAMPP.
所以在这里,我绝对不顾一切地试图让某些事情奏效。我知道我想做的不是面向对象编程,也不是 100% 的最佳实践。它不适用于实时网站,我只是在 XAMPP 上学习一些基本的 PHP 概念。
What I am trying to dois to make the $conn variable inside my database connection function accessible to all other functions that need it. I am thinking of passing it as a parameter, but how can this be done? I prefer not using PHP's "global" or $GLOBALS. My method of working right now is with mysqli using procedural methods.
我想要做的是使我的数据库连接函数中的 $conn 变量可供所有需要它的其他函数访问。我正在考虑将它作为参数传递,但是如何做到这一点?我不喜欢使用 PHP 的“全局”或 $GLOBALS。我现在的工作方法是使用程序方法使用 mysqli。
For example I have something like this:
例如我有这样的事情:
function db () {
$conn = mysqli_connect ("localhost", "root", "", "database");
}
function someFunction () {
$result = mysqli_query ($conn, "SELECT * FROM examples)
}
I never found the answer to my issue...most solutions which I recently got familiar with are OOP based or use somewhat questionable methods.
我从来没有找到我的问题的答案……我最近熟悉的大多数解决方案都是基于 OOP 的,或者使用了一些有问题的方法。
------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------- -------------------------------------------------- --------------------------------
SOLUTION A - I would rather avoid not having my connection in a wrapper and using global variables:
解决方案 A - 我宁愿避免在包装器中没有我的连接并使用全局变量:
global $conn = mysqli_connect ("localhost", "root", "", "database");
global $conn;
function someFunction () {
global $conn;
$result = mysqli_query ($conn, "SELECT * FROM examples)
}
SOLUTION B - I am not ready for OOP yet but I know this works. The point is I want to learn something different:
解决方案 B - 我还没有为 OOP 做好准备,但我知道这行得通。关键是我想学习一些不同的东西:
class Database
{
private static $conn;
public static function getObject()
{
if (!self::$conn)
self::$conn = new mysqli("localhost", "root", "", "database");
return self::$conn;
}
}
function someFunction () {
$result = mysqli_query (Database::$conn, "SELECT * FROM examples)
}
SOLUTION C - Not using functions at all...just keeping it unwrapped which I dont find very practical in the long term:
解决方案 C - 根本不使用函数……只是将它展开,从长远来看,我认为这不太实用:
$conn = mysqli_connect ("localhost", "root", "", "database");
$result = mysqli_query ($conn, "SELECT * FROM examples)
------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------- -------------------------------------------------- --------------------------------
THE SOLUTION I AM TRYING TO ACHIEVE:
我正在努力实现的解决方案:
function db () {
$conn = mysqli_connect ("localhost", "root", "", "database");
return $conn;
}
function someFunction () {
$conn = db ();
$result = mysqli_query ($conn, "SELECT * FROM examples)
}
OR Something like this where I just pass in the connection as a parameter or something (pseudo code at the moment)
或者像这样的东西,我只是将连接作为参数或其他东西传入(目前是伪代码)
function db () {
$conn = mysqli_connect ("localhost", "root", "", "database");
}
function someFunction ($conn) {
$result = mysqli_query ($conn, "SELECT * FROM examples)
}
------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------- -------------------------------------------------- --------------------------------
So how do I achieve something like the last two but which actually works. Is this concept possible?
那么我如何实现类似于最后两个但实际上有效的东西。这个概念可行吗?
回答by Reed
Your Desired Solution:This should work, and you'll only make one connection.
您想要的解决方案:这应该可行,而且您只会建立一个连接。
function db () {
static $conn;
if ($conn===NULL){
$conn = mysqli_connect ("localhost", "root", "", "database");
}
return $conn;
}
function someFunction () {
$conn = db();
$result = mysqli_query ($conn, "SELECT * FROM examples);
}
If you used the function someFunction($conn)
, that would make your code much messier, since you wouldn't actually have universal access to $conn
from anywhere.
如果您使用function someFunction($conn)
,那会使您的代码更加混乱,因为您实际上无法$conn
从任何地方普遍访问。
You should go with Solution BIMO. That way, you can have simple access to it Database::$conn
which will be consistent throughout your script. You couldshould have an initialize
function (you could use a different name if you want) that will initialize Database::$conn
, and you can then use that to initialize other things on the Database
class later, if desired.
您应该使用解决方案 BIMO。这样,您就可以简单地访问它Database::$conn
,这将在整个脚本中保持一致。你可能应该有一个initialize
(如果你愿意,你可以使用不同的名称),将初始化函数Database::$conn
,然后你可以使用的初始化其他的东西Database
,如果需要的类后,。
Solution Ais terrible. I did that for a long time (global
izing things), and it was a horrible idea. I should have never done that. But I did. And I learned. It just made code get progressively sloppier and sloppier.
解决方案 A很糟糕。我这样做了很长时间(调整global
事物),这是一个可怕的想法。我不应该那样做。但我做到了。我学会了。它只是让代码变得越来越草率。
Solution B:Database::$conn
should be public
if you want to be able to access it by Database::$conn
from anywhere. If it's private, then you would always need to call Database::getObject();
解决方案 B:如果您希望能够从任何地方访问它,Database::$conn
应该是。如果它是私人的,那么你总是需要打电话public
Database::$conn
Database::getObject();
Solution C:You're right. That would be very impractical.
解决方案 C:你说得对。那将是非常不切实际的。
Solution B rewrite:
解决方案B重写:
class Database
{
/** TRUE if static variables have been initialized. FALSE otherwise
*/
private static $init = FALSE;
/** The mysqli connection object
*/
public static $conn;
/** initializes the static class variables. Only runs initialization once.
* does not return anything.
*/
public static function initialize()
{
if (self::$init===TRUE)return;
self::$init = TRUE;
self::$conn = new mysqli("localhost", "root", "", "database");
}
}
Then... call Database::initialize()
at least once before it gets used.
然后......Database::initialize()
在它被使用之前至少调用一次。
<?php
Database::initialize();
$result = mysqli_query (Database::$conn, "SELECT * FROM examples);
?>
EDIT
编辑
- You can also call
Database::initialize()
immediately after the declaration of the class, in that PHP file. Then initializing is handled. - I'm now far more fond of something like
Database::getDb()
than accessing the$conn
property directly. Theninitialize
can be called from thegetDb()
function. Basically like the Desired Solutionbut inside a class. The class really isn't necessary, but it can be nice if you like classes, like I do.
- 您还可以
Database::initialize()
在该 PHP 文件中的类声明之后立即调用。然后处理初始化。 - 我现在
Database::getDb()
比$conn
直接访问属性更喜欢类似的东西。然后initialize
可以从getDb()
函数中调用。基本上就像Desired Solution但在一个类中。上课真的没有必要,但如果你喜欢上课,就像我一样,那会很好。
回答by s3nzoM
Pass an argument to your function like and return the connection
将参数传递给您的函数并返回连接
function db($conn){
$conn = mysqli_connect ("localhost", "root", "", "database");
return $conn;
}
回答by Hassan Saeed
simple answer just pass your $conn
variable into another calling function(instead of making new connection)
简单的答案只是将您的$conn
变量传递给另一个调用函数(而不是建立新连接)
like
喜欢
yourpage.php
你的页面.php
$conn = new mysqli($servername, $username, $password, $dbname);
someFunction ($conn)//you can add other parameters if you like
function someFunction ($conn) {
$result = mysqli_query ($conn, "SELECT * FROM examples);
}
Note:This is not good practice to always make new connection for database access.so always make connection once and use it every where.(but if your requirement different and require multiples connections then you can make multiples connections)
注意:总是为数据库访问建立新连接并不是一个好习惯。所以总是建立一次连接并在任何地方使用它。(但如果您的要求不同并且需要多个连接,那么您可以建立多个连接)
回答by Fakhar Anwar
All of the answers in this section are overkill as they are doing overhead just by creating a wrapper around a database object. For separation of concern(Maintainability) use a separate PHP file for database connection and use require_once.
本节中的所有答案都有些矫枉过正,因为它们只是通过围绕数据库对象创建包装器来增加开销。对于关注点分离(可维护性),使用单独的 PHP 文件进行数据库连接并使用 require_once。
//Inside Database_Connect.php
//内部Database_Connect.php
$db = mysqi_connect(localhost, database, password);
$db = mysqi_connect(localhost, 数据库, 密码);
Now use $GLOBALS['db'] inside your mysqli_ functions wherever needed.
现在在需要的地方使用 mysqli_ 函数中的 $GLOBALS['db'] 。
OR, initialize your script / object as
或者,将您的脚本/对象初始化为
$dbConn = $GLOBALS['db'];
$dbConn = $GLOBALS['db'];
and use $dbConn inside your mysqli_ functions wherever needed.
并在需要的地方在 mysqli_ 函数中使用 $dbConn。
回答by Subin Thomas
If you have multiple php files which require db access, then the option you can have is create a file connection.php with connection code
如果您有多个需要 db 访问的 php 文件,那么您可以选择使用连接代码创建一个文件 connection.php
<?php
$conn = mysqli_connect ("localhost", "root", "", "database");
?>
And use include_once 'connection.php';
in all other files you require a connection.
并include_once 'connection.php';
在需要连接的所有其他文件中使用 。