这个PHP代码有什么问题

时间:2011-02-14 18:02:46

标签: php php-5.3

它正在吐出synatx错误与cdoe.can的这一部分你请告诉我这段代码有什么问题

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;

解析错误:语法错误,test.php中的意外T_STRING(37)第1行的运行时创建的函数

4 个答案:

答案 0 :(得分:4)

如果您使用PHP 5.3,请不要使用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

答案 1 :(得分: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();

编辑:修正了Rocket指出的col错误。

而且Kendal Hopkins的封闭示例实际上是php 5.3 +的一种更好的方式。

答案 2 :(得分: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();

注意echo $col

之后的括号

答案 3 :(得分:0)

你无法执行

 Painting with the color $color

但你可以

 $ret_col = create_function('$color', 'return "Painting with the color ".$color;');
相关问题