php - 在 PHP 中通过引用传递数据库连接

标签 php mysql database

问题是数据库连接应该通过引用还是值传递?

对我来说,我特别质疑 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/

相关文章:

php - Windows Azure 中的非拉丁字符 URL 重写

java - 更新 : could not execute statement, 时出现 Hibernate 错误 在 'index=1' 附近使用正确的语法

database - 每个 DBMS 的所有保留字

sql - 插入从另一个表计算的值

用于转换 MySQL 表的 PHP 代码不起作用

database - 如何正确实现存储库模式?

+40k 记录的 iphone sdk sqlite 查找性能

php - 如果多个准备好的语句之一失败,则停止并恢复

php - Magento 搜索结果不包括子产品

php - 从 Woocommerce 元框访问自定义函数中的 Order 对象