簡體   English   中英

如何在 PHP wordpress 中的 function 代碼中獲取變量的預定義值

[英]how to get pre-defined value of variable inside function code in PHP wordpress

所以我有這些:

echo ('timeframe1:');echo ($timeframe);

function filter_where($where = '') {
echo ('timeframe2:');echo ($timeframe);
$where .= " AND post_date > '" . date('Y-m-d', strtotime("-$timeframe days")) . "'";
return $where;
}

echo ('timeframe3:');echo ($timeframe);

上述代碼的結果是:

timeframe1: 5
timeframe2:
timeframe3: 5

問題是,如何在 function 中獲取我的 $timeframe 值? 如您所見,在 function 中回顯 $timeframe 的結果是 null。 如何在 function 中獲取預定義的 $timeframe 值 5?

使用GLOBAL傳遞 function 之外的變量

function filter_where($where = '') {
global $timeframe; // <---- pass it as global
echo ('timeframe2:');echo ($timeframe);
$where .= " AND post_date > '" . date('Y-m-d', strtotime("-$timeframe days")) . "'";
return $where;
}

或者您將 pass $timeframe timeframe 作為參數調用到您的 function

function filter_where($where = '', $timeframe ) /* here we pass a variable into function */ {
echo ('timeframe2:');echo ($timeframe);
$where .= " AND post_date > '" . date('Y-m-d', strtotime("-$timeframe days")) . "'";
return $where;
}

致電 function:

filter_where('', $timeframe);

它不像GLOBAL的變體那么干凈,但仍然有效。

暫無
暫無

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

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