-1

为什么我不能这样做?还是我只是语法错误?

$status = function() {
    switch($job['status'])
    {   case "CREATED": return "Created by <b>$creator</b> on " . date("jS \o\\f M Y",$job['ts']); break;
        case "APPROVAL": return "Pending Approval."; break;
        case "DEFERRED": return "Marked as <b>Deferred</b> by <b>$creator</b>."; break;
        case "COMPLETE": return "Marked as <b>Complete</b>."; break;
    }
}

echo $status;
4

3 回答 3

3

匿名函数需要 PHP >= 5.3.0

$status = function($job, $creator) {
    switch($job['status'])
    {   case "CREATED": return "Created by <b>$creator</b> on " . date("jS \o\\f M Y",$job['ts']); break;
        case "APPROVAL": return "Pending Approval."; break;
        case "DEFERRED": return "Marked as <b>Deferred</b> by <b>$creator</b>."; break;
        case "COMPLETE": return "Marked as <b>Complete</b>."; break;
    }
};

echo $status($job, $creator);
于 2013-07-23T10:01:26.683 回答
1

你想要做的是一个闭包(匿名函数)。但这仅适用于 PHP >= 5.3。

正确的语法是:

$status = function($job) {
    // your switch
};

echo $status($job);

// or import $job to scope

$job = array('status' => 'CREATED');
$status = function() use($job) {
    // your switch
};

echo $status();

为什么不只是做一个正常的功能?

function getStatus($job) {
    // your switch
}

echo getStatus($job);
于 2013-07-23T10:07:44.813 回答
0


,也许你应该看看php 人变量函数匿名函数闭包

于 2013-07-23T10:02:42.567 回答