How to achevie the Polymorphism progarmme in PHP?

Hi, I'm trying to write code to achieve php polymorphism. I don't know where there is a mistake in the code. It shows the error in "Fatal error: Cannot redeclare Sample::a() ". Here is my code. Kindly solve this problem.

 <?php
 class Sample
{
public function a()
{
 echo "hi";
}
public function a($chr)
{
 for ($chr=0;$chr<10;$chr++)
 echo $chr;
}
 public function a($b,$c)
 {
for($g=$b;$g<$c;$g++)
echo $g
}
}

$s=new Sample();
$s->a();
$s->a($chr);
$s->a(1,10);
?>  

Upvotes: 1

Views: 584

Answers (4)

Wesley van Opdorp
Wesley van Opdorp

Reputation: 14941

PHP does not support method overloading...unfortunatly!

There are some funky methods to achievement something that feels like overloading, like using magic methods or wrapping sub-method calls. These don't even come close to the real thing though.

Upvotes: 4

SDC
SDC

Reputation: 14222

PHP doesn't support method overloading the way you've asked for.

The closest you can get is using dynamic arguments to fake it. Something like the following:

class dynamic {
    public function example() {
        $args = func_get_args();
        switch(count($args)) {
            case 1 : return $this->example_1arg($args[0]);
            case 2 : return $this->example_2args($args[0],$args[1]);
            //etc..
        }
    }
    private function example_1arg($arg1) {
        //....
    }
    private function example_2args($arg1,$arg2) {
        //....
    }
}

That still doesn't get you proper method overloading, because this example doesn't take into account data types. You could wire that in to a certain extent using instanceof, but you won't be able to go the whole way, since PHP also doesn't (yet) support type hinting for primitive types.

Upvotes: 0

som
som

Reputation: 4656

http://www.php.net/manual/en/language.oop5.overloading.php

See the above link. I think it will help you.

Upvotes: 0

erenon
erenon

Reputation: 19118

This is not polymorphism but the following:

class A {
    public function foo() {
        return 1;
    }
}

class B {
    public function foo() {
        return 2;
    }
}

$items = array(new A(), new B());

echo $items[0]->foo();
echo $items[1]->foo();

Upvotes: 2

Related Questions