Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Editable form fields? Reply To: Editable form fields?

#171451
__
Participant

Yeah, kinda. His example misses a big point, however. It’s more than moving everything into a function definition; it’s about making the code more flexible and usable is more situations. In his example, the function makes a nav bar and prints it. This means that you can’t use the function unless you actually want to print the nav bar, too. If you wanted to get the nav bar HTML without printing it, then you’d have to create a whole second function that duplicates most of that code. (There’s also the issue of this being no better for error handling than the original code, but we’ll set that aside for now.)

Here’s the basic PHP function syntax:

  • function keyword
  • function label (name)
  • opening paren
  • argument list
  • closing paren
  • opening curly brace
  • function body (i.e., the code)
  • closing curly brace

So, you have:

function name_of_function( $arg1,$arg2 ){
    /* code goes here */
    /* <code>return</code> statement goes here */
}

Arguments are optional. Most functions have args, but some don’t need any. You define arguments by putting varibale names inside the parens, as above. You can give arguments default values to make them optional: $arg2="default value".

return statements are also optional. If you don’t have one, the function returns “void” (i.e., nothing) when it’s done. As a general rule, most functions you write should have return values. Also as a general rule, “side effects” (things done inside a function that also change things outside the function, e.g., printing the html for a nav bar) should not happen.

Rewriting the function in that vid:

<?php
function nav_main( $dbc, $pageId ){

    $q = "select <code>id</code>,<code>label</code> from <code>pages</code>";
    $r = mysqli_query( $dbc,$q );

    $html = '<ul class="nav navbar-nav">';

    while( $nav = mysqli_fetch_assoc( $r ) ){

        $html .= ($nav['id'] === $pageId)?
            '<li class="active"><a href="'.$nav['id'].'">'.$nav['label'].'</a></li>':
            '<li><a href="'.$nav['id'].'">'.$nav['label'].'</a></li>';
    }
    $html .= '</ul>';

    return $html;
}

Instead of printing the HTML as it is generated, it is collected in the $html variable. Then, when we are done, we return that variable. Instead of having uncontrollable side effects, you simply get a string back from the function:

$nav_html = nav_main( $dbc,$pageId );

…which you can print, use to do other things, whatever.