11 Oct 2019
PHP 基本

允許臨時建立一個沒有指定名稱的函式,經常用作回撥函式引數的值

$greet = function() {
    echo 'Hello there.';
};

$greet();

Untitled

傳值進去

$name = 'friend';
$greet = function() use ($name) {
    echo 'Hello there, ' . $name . '.';
};

$greet();

Untitled

注意,如果這樣寫,會導致語法錯誤,盡管看起來很合理…

$greet = function(name) {
    echo 'Hello there, ' . $name . '.';
};

傳多個值進去

$name = 'friend';
$ben = 'Ben';

$greet = function() use ($name, $ben) {
    echo 'Hello there, ' . $name . ', ' . $ben . '.';
};

$greet();

Untitled

Tags: #PHP

回上一頁