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
PHP:
-
class named
-
{
-
public function clean()
-
{
-
foreach ($this as $key => $value) {
-
-
}
-
}
-
-
private function __call($method, $arguments)
-
{
-
if (isset($this->
$method)) {
-
return $this->$method;
-
} else {
-
return $arguments[0];
-
}
-
}
-
}
-
-
$named = new named();
-
-
function inputText($name, $maxlength = 5)
-
{
-
-
-
$html = "<input type=\"text\" name=\"$name\" ";
-
$html .= "maxlength=\"" . $named->maxlength($maxlength) . "\" ";
-
-
$html .= " />\n";
-
-
$named->clean();
-
-
return $html;
-
}
-
-
echo inputText
('input_name');
-
-
echo inputText
('input_name',
$named->
maxlength =
10);
-
-
/*
-
Outputs:
-
<input type="text" name="input_name" maxlength="5" />
-
<input type="text" name="input_name" maxlength="10" />
-
*/
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:
PHP:
-
class named
-
{
-
-
-
public function clean()
-
{
-
foreach ($this as $key => $value) {
-
-
}
-
}
-
-
private function __set($nm, $val)
-
{
-
$this->x[$nm] = $val;
-
}
-
-
private function __get($nm)
-
{
-
-
-
-
return $$nm;
-
} else {
-
return $this->x[$nm];
-
}
-
}
-
}
-
-
class form extends named
-
{
-
function inputText($name)
-
{
-
$this->maxlength = 5;
-
$this->size = 10;
-
-
$html = "<input type=\"text\" name=\"$name\" ";
-
$html .= "maxlength=\"" . $this->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:
-
<input type="text" name="input_name" maxlength="5" size="10" />
-
<input type="text" name="input_name" maxlength="5" size="20" />
-
*/
$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.