簡體   English   中英

如何正確獲取 PHP 函數的返回值?

[英]How to properly get a return value from a PHP function?

下面的代碼片段從第二個回聲輸出生成“12290”,但第三個仍然為零。

如何從mytest()函數獲得正確的返回值?

$testId = 0;
echo 'first: ' . $testId . '<br>';

function mytest($postId) {
    if (get_post_type($postId) === 'artist') {
        $testId = $postId;
    }
    echo 'second: ' . $testId . '<br>';
    return $testId;
}

mytest(12290);
echo 'third: ' . $testId . '<br>';

您忘記再次將返回值分配給變量。
應該是這樣的:

$testId = 0;
echo 'first: ' . $testId . '<br>';

function mytest($postId) {
    if (get_post_type($postId) === 'artist') {
        $testId = $postId;
    }
    echo 'second: ' . $testId . '<br>';
    return $testId;
}

$testId = mytest(12290);
echo 'third: ' . $testId . '<br>';

代替:

mytest(12290);
echo 'third: ' . $testId . '<br>';

嘗試:

echo 'third: ' . mytest(12290) . '<br>';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM