在函数参数中引用过程PHP中的现有对象


Reference existing object in procedural PHP in a function argument

让我们有以下代码:

$mysqli = new mysqli("hostname", "user", "password", "database");
function close () {
    $mysqli->close();
    die;
}

这将不起作用,因为函数close()的参数中没有引用$mysqli对象。是否可以在不修改参数列表(没有参数)的情况下引用此对象?为了解决这个问题,我们假设我不能将$mysqli作为close()的参数,我必须以另一种方式引用它。这能做到吗?

谢谢。

EDIT:尽管我使用了面向对象的mysqli,但这是程序性PHP。我的代码中没有类。

如果你想坚持使用过程函数,你有两个选项:

1.

 function close($mysqli) {
   $mysqli->close();
   die; // This probably shouldn't be here.
  }

2.

function close() {
  global $mysqli;
  $mysqli->close();
  die; // This probably shouldn't be here.
}
function close () {
    $GLOBALS['mysqli']->close();
    die;
}