Re: How do YOU set default function/method params?

From: Date: Tue, 06 Oct 2009 07:18:15 +0000
Subject: Re: How do YOU set default function/method params?
References: 1 2 3 4  Groups: php.general 
Request: Send a blank email to php-general+get-298629@lists.php.net to get a copy of this message
paragasu wrote:
why bother, i use available good library http://swiftmailer.org/
Ok, bad example. I already use SwiftMailer. My "problem" though has nothing to do with sending an email. I should have known someone would take it too literally. Think a little more general. This is not a specific thing to simply sending an email. Could be database method calls from a class object, HTML CGI function, etc... As for a different example. Say you had a function that you had to pass (multiple) arguments to. But, with those arguments, you had defaults that you would like to inside the function even if they were not sent when you called your function. But you do not want to be forced into entering ALL the arguments of a function call in a certain order. Try this function createHTMLBox($title, $content, $params=array() ) {
    $defaults = array(
        'id'     = uniq(),
        'class'  = 'box',
        'encode' = TRUE,
    );
    $params += $defaults;
    if ( $params['encode'] ) {
        $title   = htmlspecialchars($title);
        $content = htmlspecialchars($content);
    }
    # Obviously, I will be using the DomDocument class for this in the real world
    # But for simplicities sake, I used the following.
    $box = <<<BOX
<div id="{$params['id']}" class="{$params['class']}"> <h4 class="boxTitleBar">{$title}</h4> <div class="boxContent">{$content}</div> </div> BOX;
    return $box;
} Then, I call it like this: echo createHTMLBox('This is my TITLE',
               '<ul><li>Item 1</li><li>Item 2</li></ul>',
               array('encode' => FALSE));
echo createHTMLBox('This is my TITLE',
               '<ul><li>Item 1</li><li>Item 2</li></ul>');
Both of the above will have different output to the screen. Hope this clears things up. -- Jim Lucas "Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them." Twelfth Night, Act II, Scene V by William Shakespeare

« previous php.general (#298629) next »