在 PHP 中,函數有兩種類型,即內建函數和使用者定義函數。有很多內建函數可以由程式設計師或開發人員直接從程式中呼叫。這些內建函數對於要執行的任務具有特定的意義。使用者定義函數是由包含要針對應用程式執行的程式碼的程式專門開發的。開發人員編寫一組必須根據應用程式中的要求執行任務的程式碼。
廣告 該類別中的熱門課程 PHP 開發人員 - 專業化 | 8 門課程系列 | 3次模擬測驗開始您的免費軟體開發課程
網頁開發、程式語言、軟體測試及其他
PHP 中有兩種類型的函數,即內建函數和使用者定義函數。這些函數在程式中用於執行各種任務。 PHP 中定義了大量的函數,可以在程式的任何地方使用。雖然它有很多不需要一遍又一遍地編寫程式碼的優點,而且功能都是自帶的,但開發者可以輕鬆使用內建的功能。但所有內建函數都有預先定義的意義,並且本身執行特定的任務。因此,開發人員開始開發使用者定義的函數,開發人員可以在任何函數內編寫特定的任務程式碼,並且可以在程式中的任何位置使用。使用者定義的函數在程式中的類別或程式的方法中調用,以根據應用程式的要求執行任務。
在 PHP 中,使用者定義的函數必須使用關鍵字「function」聲明。如果我們聲明了函數名稱並且將要執行的程式碼寫在裡面,那麼它就可以在程式中的任何地方呼叫。
文法:
function function_name() { //statements }
在上面的語法中,function_name是程式中要呼叫的函數的名稱,function是用來宣告函數的關鍵字。在 PHP 中,函數是用 function 關鍵字宣告的,前綴是函數名,程式中的函數呼叫只需在需要的地方呼叫函數名即可。
讓我們透過範例來了解 PHP 中呼叫函數的概念。
在下面的例子中,函數Write_Output是函數的名稱,並且在下面的同名程式中呼叫該函數。此行將呼叫定義的函數並執行函數內編寫的語句,並在程式碼的最後一條語句執行後退出。
代碼:
<?php function Write_Output() { echo "This is the sample example of a function!"; } Write_Output(); ?>
輸出:
1.在 PHP 中,函數可以是參數化函數,即將參數傳遞給函數。參數就像我們在程式中定義的變數一樣。我們可以簡單地在括號內的函數名稱後面傳遞參數,並且可以透過在參數之間添加逗號來添加任意數量的參數。這些參數將在呼叫函數時進行映射。如果在呼叫函數時沒有傳遞正確數量的參數,它將拋出錯誤。
代碼:
<?php function Employee($ename) { echo "$ename Patil \n"; } Employee("Akash"); Employee("Prakash"); ?>
輸出:
在上面的範例中,Employee 是函數的名稱,ename 是在宣告中傳遞給函數的參數。 Employee 函數在函數宣告下方調用,並且值在調用時傳遞給函數。程式的輸出將是呼叫函數時傳入函數的員工姓名。
2.在下面的範例中,列印了員工姓名,並且還列印了員工 ID。當一個組織有大量資料要儲存在資料庫中時,我們只需編寫此類程式碼即可輕鬆處理資料。
代碼:
<?php function Employee($ename, $id) { echo "Employee name is $ename and Employee id is $id \n"; } Employee("Lakshmi","780540"); Employee("Rohit","780541"); Employee("Jenny","780542"); ?>
輸出:
在 PHP 中,變數並非嚴格地基於資料類型,取決於其值或資料。資料類型是鬆散耦合的,不遵循任何嚴格的規則。因此我們也可以對具有不同資料類型的變數進行加法、減法和多種運算。
As we have seen all the examples, we can clearly see that the user-defined functions are more beneficial to the developer as it helps a lot from an application perspective and also is used to get the desired output. The goal of using functions in a particular program is that it can create his own code and develop the application based on requirements.
Code:
<?php function mulNumbers(int $x, int $y) { return $x * $y; } echo mulNumbers(5, 13); ?>
Output:
As we have seen in the above example that the integer can be multiplied with a string and a string can be used along with float etc. So PHP is a loosely typed language. In the above example, we could clearly see that the variable x and y are declared as integer and while calling they just use one variable as integer and another one as a string and the desired output also gets fetched.
In this article, we discussed how to call functions in PHP i.e. user-defined function. Then we discussed different forms of user-defined functions and syntax with example. The functions can be written for a specific application and to perform a specific task i.e. calculation of payroll, adding new entries, etc. So the developer can easily modify the code for the flexibility and can call it anywhere in the program.
以上是PHP呼叫函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!