![](/img/trans.png)
[英]Store the return value from an anonymous function into a variable outside its scope
[英]Store function return value into variable
我正在將Wordpress插件用於自定義字段。
the_field('something')
我按下,只是回顯返回值。
無法將返回值存儲到變量中嗎?
因為$a = the_field('something');
也呼應。
我真正想做的是
if(the_field('something')) {
// echo the_field('something')
}
else
// do something
但無論哪種方式,它只會在頁面中回顯
就像我在評論中說的那樣,如果函數僅回顯某些內容,則沒有返回值。 但是仍然有一種捕獲輸出的方法。
考慮這個功能
function doStuff()
{
echo 'hello';
}
您不能從中獲得返回值,但是可以使用ob_functions捕獲內容:
ob_start();
doStuff();
$output = ob_get_contents();
ob_end_clean();
現在$output
包含該函數的輸出,而不是已打印。
我不喜歡WordPress。 看來他們有兩個(或更多)檢索任何東西的功能。 一個回聲它the_title()
和其他回報它get_title()
對於這個插件,它應該可以工作:
if($field = get_field('something')) {
echo $field;
}
else
// do something
}
如果您遇到回顯且不返回值的東西,並且沒有相應的函數返回某物,則:
ob_start();
the_something();
$output = ob_get_clean();
// use $output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.