我应该将 $mysqli 变量传递给每个函数吗?

2021-12-25 00:00:00 function database php mysql mysqli

我在从 mysql_* 传递到面向对象的 mysqli 时遇到了一个小问题.

I am having a little problem passing from mysql_* to mysqli object oriented.

我的 index.php 文件的结构就像包含两个文件:

My index.php file is structured like including two files:

include('connect.php');
include('function.php');

connect.php 文件包含:

The connect.php file contains:

<?php
$mysqli = new mysqli("localhost", "root", "test", "test");

if (mysqli_connect_errno($mysqli)) {
    printf("Connection failed: %s
", mysqli_connect_error());
    exit();
}
?>

在 function.php 文件中有一个名为 showPage 的函数,它不接受任何参数,但使用 $mysqli强> 连接,如...

In the function.php file there is a function called showPage that takes no arguments but uses the $mysqli connection, in lines like...

$result = $mysqli -> query("SELECT * FROM $table ORDER BY ID DESC"); // Seleziono tutto il contenuto della tabella

如果不将 $mysqli 变量传递给函数,我就无法使其正常工作,但是当我使用 mysql_* 不推荐使用的函数时,这不是必需的!

I cannot manage it to work without passing to the function the $mysqli variable, but this was not necessary when I used mysql_* deprecated functions!

我能理解为什么吗?解决这个问题的最佳方法是什么?

Can I understand why, and what's the best way to resolve this?

推荐答案

用户定义的函数在 PHP 中有自己的变量作用域.需要将$mysqli作为参数传递给函数,或者用global $mysqli启动函数.

User-defined functions have their own variable scope in PHP. You need to pass $mysqli to the function as a parameter, or start the function with global $mysqli.

这个确切的问题作为变量作用域的一个例子给出页面:

This exact problem is given as an example on the Variable scope page:

然而,在用户定义的函数中,局部函数作用域是介绍.默认情况下,函数内部使用的任何变量都是仅限于局部函数范围.比如这个脚本不会产生任何输出,因为 echo 语句指的是本地$a 变量的版本,它没有被赋值在这个范围内.你可能会注意到这有点不同来自 C 语言,因为 C 中的全局变量是自动的可用于函数,除非被本地特别覆盖定义.这可能会导致一些问题,因为人们可能无意中更改了全局变量.PHP中的全局变量必须如果要在函数中使用,则在函数中声明为全局那个功能.

However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example, this script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

<?php
$a = 1; /* global scope */ 

function test()
{ 
    echo $a; /* reference to local scope variable */ 
} 

test();
?>

相关文章