0

when doing something like

$date = mktime();
$xxx = 'if ( date("N",$date ) == 1 ) { return TRUE; } else { return FALSE; }';
$yyy = eval( $xxx );
echo $yyy;

it works.

But when doing something like

$date = mktime();
$xxx = '( date("N",$date) == 1 ? return TRUE : return FALSE );';
$yyy = eval( $xxx );
echo $yyy;

I get an error like

Parse error: syntax error, unexpected T_RETURN in /my_path/my_file.php(107) : eval()'d code on line 1

Why ?

0

2 Answers 2

4

This has nothing at all to do with eval.

Let's create the real testcase:

<?php
function foo()
{
   $date = mktime();
   ( date("N",$date) == 1 ? return TRUE : return FALSE );
}

foo();
?>

Output:

Parse error: syntax error, unexpected T_RETURN on line 5

return is a statement, not an expression, so you can't nest it into an expression which is what you're trying to do here. The conditional operator is not a one-line replacement for if/else.

To use the conditional operator properly:

return (date("N",$date) == 1 ? TRUE : FALSE);

which simplifies to just:

return (date("N",$date) == 1);

In your code, that looks like this:

$date = mktime();
$xxx = 'return (date("N",$date) == 1);';
$yyy = eval($xxx);
echo $yyy;
Sign up to request clarification or add additional context in comments.

Comments

3

I'm pretty certain that should be

$xxx = 'return ( date("N",$date) == 1 ? TRUE : FALSE );';

The things generated by a ternary operator are values (expressions) rather than commands.

1 Comment

Thanks, sometimes I do not see the forest because of all the trees ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.