问题是数据库连接应该通过引用还是值传递?
对我来说,我特别质疑 PHP 到 MySQL 的连接,但我认为它适用于所有数据库。
我听说在 PHP 中,当您将变量传递给函数或对象时,它会被复制到内存中,因此会立即使用两倍的内存。我还听说只有在对值进行更改后才会复制它(例如从数组中添加/删除键)。
在数据库连接中,我认为它正在函数内进行更改,因为查询可能会更改最后插入 id 或 num 行之类的内容。 (我想这是另一个问题:是像 num rows 和 insert id 这样存储在连接中还是实际调用回数据库?)
那么,如果连接是通过引用或值传递的,内存或速度是否重要? PHP 4 和 5 有区别吗?
// $connection is resource
function DoSomething1(&$connection) { ... }
function DoSomething2($connection) { ... }
最佳答案
PHP 资源是一种特殊类型,它本身就是一个引用。按值传递或按引用显式传递不会有什么不同(即,它仍然是一个引用)。您可以在 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 - 在 PHP 中通过引用传递数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/241311/