<?
function foo($return = false) {
$x = '12345';
$return ?
return $x : // here it fails
echo $x;
}
echo foo(true);
?>
It says "Parse error: syntax error, unexpected 'return' (T_RETURN) in..."
Why!? :)
<?
function foo($return = false) {
$x = '12345';
$return ?
return $x : // here it fails
echo $x;
}
echo foo(true);
?>
It says "Parse error: syntax error, unexpected 'return' (T_RETURN) in..."
Why!? :)
You can't use inline ifs in this way. They are normally used like this:
echo ($return ? x : "false");
Your code should be like this:
<?
function foo($return = false) {
$x = '12345';
if($return)
{
return $x
}
else
{
echo $x;
}
}
echo foo(true);
?>
(more confusing for some), you don't need to add the else
statement, as if the if
statement is satisfied, it will return a value, thus exiting the function, which means if the if
statement is not satisfied, it will go to the echo
anyway:
<?
function foo($return = false) {
$x = '12345';
if($return)
{
return $x
}
echo $x;
}
echo foo(true);
?>
You can use the print function instead of echo:
<?php
function foo($return = false) {
$x = '12345';
return $return ? $x : print($x);
}
$x = foo(true);
More elegant is Styphons way from the comments:
if ($return) { return $x; } echo $x;