I’m trying to get my code error and notice free. Therefore I should check every variable I want to echo. The specific case I am interested in, is a “new” page that can also act as an “edit”. If something was selected, it displays the edition page with the fields filled in with the content to be edited. If there was nothing selected it’s the same page but with empty fields. This gives an idea of what I mean:
<li class="bordertop">
<label>Recommended knowledge</label>
<input class="first_input" name="recommended[]" value="<?php if (count ($Subject->retrieveLink('recommended')) > 0) echo current($Subject->retrieveLink('recommended')); ?>" placeholder="Title"/>
<input class="second_input" name="recommended_url[]" value="<?php if (key ($Subject->retrieveLink('recommended')) != null) echo key($Subject->retrieveLink('recommended')); ?>" placeholder="http://www.example.com"/>
</li>
I really don’t like THAT much code in my page. I am trying to separate as much as I can logic from presentation as well as keeping an OOP approach. I was thinking about doing something similar to this:
// Check + echo
function checko($arg = null)
{
if (!is_array($arg))
if (!empty($arg))
echo $arg;
}
But that also seems to be calling for trouble in the future (echoing from inside doesn’t let me further modify the string and it doesn’t feel like a ‘proper’ solution at all). There are many of variables that I want to check and echo which sometimes will be filled and some times empty. What’s the best approach for this? I know I could repeat my code everywhere by doing the if (empty($variable)) echo $variable, but:
-
This doesn’t work (as of PHP 5.4, I believe it’ll work in 5.5) with returning values from objects. This is my main concern, since I use that very often.
-
I’d have too much repeated code. No
Nope, you shouldn’t.
Look, these notices aren’t only to make your busy fighting them. They are for help, not to make your code complicated.
You just need to be sure what variables you operate. And adding bulk
if(empty())won’t do any good.That’s indeed too much code for the template. Some of it should be moved into controller
Prepare your data before calling template, and then make it plain