加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2021-07-06 05:22:18 所属栏目:大数据 来源: https://www.jb51.cc
导读:我有一个小问题从mysql_ *传递到mysqli面向对象. 我的index.PHP文件的结构类似于包含两个文件: include('connect.PHP');include('function.PHP'); connect.PHP文件包含: ?PHP$MysqLi = new MysqLi("localhost", "root", "test", "test");if (MysqLi_connec

我有一个小问题从mysql_ *传递到mysqli面向对象.

我的index.PHP文件的结构类似于包含两个文件:

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

connect.PHP文件包含:

<?PHP
$MysqLi = new MysqLi("localhost", "root", "test", "test");

if (MysqLi_connect_errno($MysqLi)) {
    printf("Connection Failed: %sn", MysqLi_connect_error());
    exit();
}
?>

在function.PHP文件中有一个名为showPage的函数,该函数不带参数但使用$MysqLi连接,在……之类的行中

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

如果不传递$MysqLi变量的函数,我无法管理它,但是当我使用MysqL_ *不推荐的函数时,这不是必需的!

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

解决方法:

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

这个确切的问题在Variable scope页面上作为示例给出:

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();
?>

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读