問題描述
我在從 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();
?>
這篇關于我應該將 $mysqli 變量傳遞給每個函數嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!