在PHP中通过引用传递数据库连接 [英] Passing database connection by reference in PHP
问题描述
问题是如果一个数据库连接应该通过引用或按值传递?
The question is if a database connection should be passed in by reference or by value?
对我来说,我特别问一个PHP到MySQL的连接,认为它适用于所有数据库。
For me I'm specifically questioning a PHP to MySQL connection, but I think it applies to all databases.
我听说在PHP中传递一个变量到一个函数或对象,它被复制在内存中,因此使用两次多记忆。我还听说,只有在对值进行更改(例如,从数组中添加/删除一个键)后才会复制。
I have heard that in PHP when you pass a variable to a function or object, that it is copied in memory and therefore uses twice as much memory immediately. I have also heard that it's only copied once changes have been made to the value (such as a key being added/removed from an array).
在数据库连接中,我认为它是在函数内改变,因为查询可以改变像最后一个插入id或num行。 (我想这是另一个问题:像num行和插入id存储在连接或实际调用回到数据库的事情)。
In a database connection, I would think it's being changed within the function as the query could change things like the last insert id or num rows. (I guess this is another question: are things like num rows and insert id stored within the connection or an actual call is made back to the database?)
如果连接通过引用或值传递,它是内存或速度明智?是否有区别PHP 4 vs 5?
So, does it matter memory or speed wise if the connection is passed by reference or value? Does it make a difference PHP 4 vs 5?
// $connection is resource
function DoSomething1(&$connection) { ... }
function DoSomething2($connection) { ... }
推荐答案
PHP资源是一种特殊类型,它本身就是一个引用。通过值或通过引用显式传递它不会产生差异(即,它仍然是引用)。你可以在PHP4下自己检查:
A PHP resource is a special type that already is a reference in itself. Passing it by value or explicitly by reference won't make a difference (ie, it's still a reference). You can check this for yourself under PHP4:
function get_connection() {
$test = mysql_connect('localhost', 'user', 'password');
mysql_select_db('db');
return $test;
}
$conn1 = get_connection();
$conn2 = get_connection(); // "copied" resource under PHP4
$query = "INSERT INTO test_table (id, field) VALUES ('', 'test')";
mysql_query($query, $conn1);
print mysql_insert_id($conn1)."<br />"; // prints 1
mysql_query($query, $conn2);
print mysql_insert_id($conn2)."<br />"; // prints 2
print mysql_insert_id($conn1); // prints 2, would print 1 if this was not a reference
这篇关于在PHP中通过引用传递数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!