Question

I'm building my first application with Kohana, and using a basic templating system within that. In my templates I want to echo variables for the various contents of the page, but only if each variable is set, and I want to keep the code in the templates as short as possible, so something like this:

<?=$foo?>

works fine if the variable is set, but if it's not I get a notice. So I thought a ternary operator would do the trick nicely:

<?=$foo?:''?>

according to the PHP manual, from 5.3 it's ok to leave out the middle part and the above should output nothing if the variable isn't set, but I still get an error notice."Notice: Undefined variable: foo in /"

I can get the desired result with a slight alteration to suppress the notice:

<?=@$foo?:''?>

but I know that's generally not beset practice and would like a better solution if possible, while still keeping the code to a minimum in the template files.

the following works, but it's not as concise (mainly because my actual variables can be quite long):

<?=isset($foo)?$foo:'';?>

am I missing something or doing something wrong?

Was it helpful?

Solution

The ternary operation is not meant to replace checking with isset() - it needs it's variable defined or else you get a notice.

Template engines usually offer a way to use a default value instead, but they also do not use pure PHP code. You you are out of luck here: Either suppress the notice, or use the longer code variant. Or ensure that every variable is set, which enables you to consider any notice an error.

OTHER TIPS

To avoid notices for undefined variables, you can create custom function that takes first parameter by reference

function tplvar(&$value, $default = '') {
    return ($value !== null) ? $value : $default;
}

<?=tplvar($foo, 'bar');?>

Uninitialized variables passed by reference will be seen as nulls.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top