Search code examples
phpphp-5.3

what is wrong with this php code


It is spitting the synatx error with this part of cdoe.can you please tell me what is wrong with this code

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;

Parse error: syntax error, unexpected T_STRING in test.php(37) runtime-created function on line 1


Solution

  • Your Function body is not valid Php code.

    Maybe you should write it

    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();
    

    Edit: Fixed the col error Rocket pointed out.

    And also the closure example Kendal Hopkins has is actually an nicer way for php 5.3+.