2014-12-02 44 views
0

我可以使用函數作爲另一個函數中參數的默認值嗎?在下面的例子中,我試圖使用WordPress的功能get_the_title()作爲默認值:您可以使用函數作爲PHP中另一個函數的默認參數嗎?

function GetPageDepartment($department = get_the_title()) { 
    return $department; 
} 

原樣,括號是導致解析錯誤。有沒有辦法解決這個問題,還是我必須將函數值傳遞給默認值之外的某個變量?

我知道這裏的實際代碼將在很大程度上沒有意義的,因爲它只是返回get_the_title(),但它只是作爲一個例子,因爲我實際上做的說法是不質疑,認爲相關。

+2

只要功能是在循環中調用,您可以用'get_the_title()'你的函數中,沒有將它作爲一個參數。 – rnevius 2014-12-02 08:47:02

+0

@mevius:所以我可以!這有效地解決了我的實際的問題,但我會離開的問題了,因爲我很好奇在WordPress的PHP獨家答案。謝謝! – BFWebAdmin 2014-12-02 08:52:15

+1

BTW:你已經提到的,這只是一個例子,但是:你GETSomething功能打印出一些東西。 – VolkerK 2014-12-02 08:53:05

回答

1

答案是「不,是,但......尚......」。
不,使用PHP 5.6,您不能將函數指定爲函數/方法的默認值。
是的,你可以指定一個字符串,如果您使用的參數/變量在功能方面,即echo $department();,該字符串將被視爲一個函數的名稱和get_the_title()將被調用。但是......你不得不依賴字符串 - >函數名稱關係。然而...誰在乎呢?


編輯:爲您考慮....

<?php 
function get_the_title() { return "the title"; } 

function GetPageDepartment(callable $department=null) { 
    if (null==$department) { 
     $department = 'get_the_title'; 
    } 
    return '<'.$department().'>'; 
} 


echo GetPageDepartment(); 
+1

我不在乎,@VolkerK。我在意。 – BFWebAdmin 2014-12-02 08:52:58

+1

我明白了......所以你想要更嚴格一些。 – VolkerK 2014-12-02 08:59:33

0

不,你不能 使用此代碼

<?php 

function get_the_title(){ 
    return 'this is the title'; 
} 
$temp = get_the_title(); 
function GetPageDepartment($department) { 
    echo $department; 
} 

GetPageDepartment($temp); 
0

最後,我撲通:

function GetPageDepartment($department = null) { 
    $department = $department ?: get_the_title(); //Sets value if null. 
} 

其中設置$ departmen的值如果沒有設置其他值,則返回get_the_title()。

相關問題