2013-03-19 70 views
0

我有一個PHP函數,基本上是這樣的化妝功能可見switch語句

$to_echo = prepare(2); 
echo $to_echo; 

function prepare($id){ 

    switch($id){ 
     case 1: 
     $res = format1(); 
      break; 
     case 2: 
     $res = format2(); 
      break; 
    } 

    function format1(){ 
     return "asdf"; 
    } 

    function format2(){ 
     return "1234"; 
    } 

    return $res; 

} 

但我發現了switch語句中的錯誤Fatal error: Call to undefined function format2() in line...

能以某種方式在$res看不到功能format1format2?我怎樣才能讓它訪問該功能?

It works like this in javascript,但PHP有很多我不明白,所以也許這不是問題;

+0

@Jocelyn Line 19 – 1252748 2013-03-19 18:57:07

+0

相關問題:[在函數定義之前調用函數](http://stackoverflow.com/q/3559875/1409082) – Jocelyn 2013-03-19 18:59:11

回答

6

你可以嘗試這樣的:

$to_echo = prepare(2); 
echo $to_echo; 

function prepare($id){ 
switch($id){ 
    case 1: 
    $res = format1(); 
    return $res; 
    break; 
    case 2: 
    $res = format2(); 
    return $res; 
    break; 
} 

} 

function format1(){ 
    return "asdf"; 
} 

function format2(){ 
    return "1234"; 
} 
+0

這可行。但是,switch語句的內部如何訪問父級外部的函數,甚至不能訪問其父級的子級? ^^謝謝! – 1252748 2013-03-19 18:56:22

+1

您可以訪問在頁面上編寫的所有功能,或者如果您包含任何文件,並且您有任何功能,那麼您也可以在開關盒內訪問該功能。 – 2013-03-19 18:57:44

1

與您的代碼的事情是,需要聲明之前使用的功能(在函數中時):

function prepare($id){ 
    function format1(){..} 
    function format2(){..} 
    //do prepare here 
    switch($id){..} 
} 

然而,如果你在函數之外聲明函數,它們可以在函數之前或之後出現。

function format1(){..} 
function prepare($id){..} 
function format2(){..} 
+0

是的,如果你移動開關上方的兩個內部函數,它將起作用 – 2013-03-19 19:02:23

1

嵌套函數format1()format2()declared直到函數的調用準備(...)已經取得進展。但是在目前的順序中,這些功能的聲明發生在switch-statement之後。因此他們沒有按時出席。

您應該嘗試將這些函數聲明放在prepare(...)函數的頂部,或根本不使用嵌套。我會推薦後者。

+0

有意義。謝謝! – 1252748 2013-03-19 19:22:46