2011-02-14 108 views
0

它與cdoe.can請你告訴我這部分吐synatx錯誤什麼是錯的這個代碼什麼是錯的這個PHP代碼

class House{ 
    private $color; 

    public function paint($color){ 
     $ret_col = create_function("\$color", "Painting with the color \$color"); 
     return $ret_col;  
    } 
} 

$hs = new House(); 
$col = $hs->paint('red'); 
echo $col; 

解析錯誤:語法錯誤,測試意外T_STRING .php(37)第1行運行時創建的函數

+5

`使用顏色$ color`繪製不是有效的PHP語法。 – 2011-02-14 18:03:44

回答

3

您的函數體是無效的PHP代碼。

也許你應該把它寫

class House{ 
    private $color; 

    public function paint($color){ 
     $ret_col = create_function("\$color", "return \"Painting with the color \$color\";"); 
     return $ret_col;  
    } 
} 

$hs = new House(); 
$col = $hs->paint('red'); 
echo $col(); 

編輯:修正了山坳誤差火箭指出。

而且Kendal Hopkins的關閉示例對於php 5.3+來說實際上是一個更好的方法。

+0

@david:當我使用相同的代碼時,它將我輸出爲「lambda_2」,其中iam預計「繪製顏色爲紅色」 – Someone 2011-02-14 18:07:27

+1

`$ col`是一個函數,因此您需要`echo $ col()`。 – 2011-02-14 18:09:01

0

不能執行

Painting with the color $color 

,但你可以

$ret_col = create_function('$color', 'return "Painting with the color ".$color;'); 
1

create_function第二個參數必須是有效的PHP字符串。 你應該這樣做:

create_function("$color", 'return "Painting with the color" . $color;'); 

而且你有另一個錯誤:當你做return $ret_col;您返回lambda函數不是lambda函數的返回值,所以你必須糾正你的代碼:

class House{ 
    private $color; 

    public function paint($color){ 
     $ret_col = create_function("$color", 'return "Painting with the color" . $color;'); 
     return $ret_col;  
    } 
} 

$hs = new House(); 
$col = $hs->paint('red'); 
echo $col(); 

注意如果您在使用PHP 5.3之後echo $col

4

支架不會使用create_function。而是使用PHP的closures。它們允許在讀取文件時檢查內部代碼,而不是在執行時更安全。此外,您必須執行閉包才能從中獲取值,您不能簡單地將它轉換爲字符串。

class House{ 
    private $color; 

    public function paint($color){ 
     $ret_col = function() use ($color) { //use a closure 
      return "Painting with the color $color"; 
     }; 
     return $ret_col;  
    } 
} 

$hs = new House(); 
$col = $hs->paint('red'); 
echo $col(); //not just $col