Treba vam Java like overloading (u Javi recimo nesto ovako):
Kôd:
class Overloading_Test
{
public void hello()
{
System.out.println("Hello Anonymous");
}
public void hello(String name)
{
System.out.println("Hello " + name);
}
public void hello(String firstName, String lastName)
{
System.out.println("Hello " + firstName + " " + lastName);
}
}
a mislili ste da PHP ne podrzava Overloading? E pa, podrzava, ali nazalost ne na tako elegantan nacin kao Java.
Malo sam se igrao veceras sa magic funkcijama (konkretno '__call') i dosao do interesantnog resenja:
PHP kôd:
<?php
class Overloading_Test
{
function __call($method_name, $arguments)
{
//list of supported methods
//only 'hello' for this test
$accepted_methods = array("hello");
//in case of unexistant method we trigger fatal error
if(!in_array($method_name, $accepted_methods))
{
trigger_error("Method <strong>$method_name</strong> doesn't exist", E_USER_ERROR);
}
//we inspect number of arguments
if(count($arguments) == 0)
{
$this->hello1();
}
elseif(count($arguments) == 1)
{
$this->hello2($arguments[0]);
}
elseif(count($arguments) == 2)
{
$this->hello3($arguments[0], $arguments[1]);
}
else
{
return false;
}
}
function hello1()
{
echo "Hello Anonymous<br>";
}
function hello2($name)
{
echo "Hello $name<br>";
}
function hello3($first_name, $last_name)
{
echo "Hello $first_name, $last_name<br>";
}
}
$ot = new Overloading_Test();
$ot->hello();
$ot->hello("John");
$ot->hello("John", "Smith");
//this one will produce fatal error
//$ot->test();
?>
Inace, koga zanima napisao sam
blog entry o tome na engleskom (nema potrebe da ga prevodim na srpski, van dpt-a to ionako nikoga ne interesuje
.