2011-02-14 102 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