Wednesday 15 June 2011

Php Reusable code, with less line Or function to make it reusable code -



Php Reusable code, with less line Or function to make it reusable code -

want create below code reusable less line instead of repeating it.ex set code in function etc. code clean , optimize.

if($pos_year) { preg_match('/^([=<>!]+)([0-9]+)$/', $pos_year, $tokens); $operator = $tokens[1]; $operand = $tokens[2]; $ck_year = create_function('$value', ' $operand = '.$operand.'; switch("'.$operator.'") { case "==": homecoming ($value==$operand); case "!=": homecoming ($value!=$operand); case "<": homecoming ($value<$operand); case "<=": homecoming ($value==$operand); case ">": homecoming ($value>$operand); case ">=": homecoming ($value>=$operand); default: throw new exception("invalid operator"); }'); } if($pos_month) { preg_match('/^([=<>!]+)([0-9]+)$/', $pos_month, $tokens); $operator = $tokens[1]; $operand = $tokens[2]; $ck_month = create_function('$value', ' $operand = '.$operand.'; switch("'.$operator.'") { case "==": homecoming ($value==$operand); case "!=": homecoming ($value!=$operand); case "<": homecoming ($value<$operand); case "<=": homecoming ($value==$operand); case ">": homecoming ($value>$operand); case ">=": homecoming ($value>=$operand); default: throw new exception("invalid operator"); }'); } $ck_year(2014); $ck_month(6);

the "rules" remove duplicate, or duplicate code simple: 1) find similar code, little or no differences 2) encapsulate code function or method 3) replace differences or potential differences arguments passed function / method.

i'm lacking context, particularly "$value" , "$tokens" variables, in case, code similar, 1 parameter (maybe 2 or 3 if 2 mentioned variables change). don't need "if" status in function - should go outside (if @ all):

function check_value($thevalue) { preg_match('/^([=<>!]+)([0-9]+)$/', $thevalue, $tokens); $operator = $tokens[1]; $operand = $tokens[2]; $ck_month = create_function('$value', ' $operand = '.$operand.'; switch("'.$operator.'") { case "==": homecoming ($value==$operand); case "!=": homecoming ($value!=$operand); case "<": homecoming ($value<$operand); case "<=": homecoming ($value==$operand); case ">": homecoming ($value>$operand); case ">=": homecoming ($value>=$operand); default: throw new exception("invalid operator"); }'); } $ck_value(2014); $ck_value(6);

php function

No comments:

Post a Comment