PHP named parameters with default values

I got a comment by Adam Kramer, whose blog I linked on the original article about PHP named parameters, saying that would be cool to have a mix of default and named parameters.

So I made a nice cup of coffe and a few hacks later, came up with a way to do it, and went to tell Adam. Well, sadly his WordPress broke my HTML text (just like mine will probably do it too), so I am posting it here.

It uses a weirdness like $named->default_var($default_var), but it works 🙂 For PHP5 only… with previous versions of PHP, every parameter would need to have its own function inside the named classes. Doable, but definitively undesirable 🙂

class named
{
    public function clean()
    {
        foreach ($this as $key => $value) {
            unset($this->$key);
        }
    }

    private function __call($method, $arguments)
    {
        if (isset($this->$method)) {
            return $this->$method;
        } else {
            return $arguments[0];
        }
    }
}

$named = new named();

function inputText($name, $maxlength = 5)
{
    global $named;

    $html = "maxlength($maxlength) . "\" ";

    $html .= " />\n";

    $named->clean();

    return $html;
}

echo inputText('input_name');

echo inputText('input_name', $named->maxlength = 10);

/*
Outputs:


*/

But Adam also said that passing named parameters with “=” is easier (and I agree). On my third cup of coffe, this is what I wrote:

class named
{
    private $x = array();

    public function clean()
    {
        foreach ($this as $key => $value) {
            unset($this->$key);
        }
    }

    private function __set($nm, $val)
   {
       $this->x[$nm] = $val;
   }

    private function __get($nm)
    {
        global $$nm;

        if (isset($$nm)) {
            return $$nm;
        } else {
            return $this->x[$nm];
        }
    }
}

class form extends named
{
    function inputText($name)
    {
        $this->maxlength = 5;
        $this->size = 10;

        $html = "maxlength . "\" ";
        $html .= "size=\"" . $this->size . "\" ";

        $html .= " />\n";

        $this->clean();

        return $html;
    }
}

$form = new form();

echo $form->inputText('input_name');

echo $form->inputText('input_name', $size = 20);

/*
Outputs:


*/

$this->maxlength = 5; and $this->size = 10; are used to set the default function “parameters”. They can’t go inside the parenthesis because otherwise the global keyword can’t access it.


Posted

in

by

Tags:

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.