PDA

View Full Version : OOP Inheritance with Same Function names but Different Parameters?


dealmaker
12-27-2005, 01:28 AM
Hi,
I have a parent and a child classes.

class parent {
function A($a1, $a2) {
...
}
}
class child extends parent {
function A() {
...
}
}


Will the function A in child override the function A in parent class? or does PHP treat them as different functions?

Many thanks.

missing-score
12-27-2005, 01:45 AM
It will over-ride the function when you create an instance of the extended class, however I believe you can still use parent::A(...) function inside the extended class, but dont quote me on this.

Velox Letum
12-27-2005, 05:05 AM
It will over-ride the function when you create an instance of the extended class, however I believe you can still use parent::A(...) function inside the extended class, but dont quote me on this.

Quoted. =)

Anyways I believe you're correct...though the class name as parent might be a bit ambiguous.

<?php
class A {
function F() {
echo 'A1<br />';
}
}
class B extends A {
function F() {
parent::F();
A::F();
echo 'A2';
}
}
$a = new A;
$b = new B;
$a->F();
$b->F();
?>

This would print out A1<br />A1<br />A1<br />A2.

dealmaker
12-27-2005, 06:25 AM
Your example's function F has no parameters. What happen if F in class A has 2 parameters, and F in class B has one parameters? When you call B.F($para), does it override F($para1, $para2) in class A?

If I remember correctly, in C++, both function name and # of parameters must be the same to be overrided.

Quoted. =)

Anyways I believe you're correct...though the class name as parent might be a bit ambiguous.

<?php
class A {
function F() {
echo 'A1<br />';
}
}
class B extends A {
function F() {
parent::F();
A::F();
echo 'A2';
}
}
$a = new A;
$b = new B;
$a->F();
$b->F();
?>

This would print out A1<br />A1<br />A1<br />A2.

Velox Letum
12-27-2005, 07:20 AM
Unlike C++, the inheritance is the same either way.

<?php
class A {
function F($para) {
echo 'A1' . $para . '<br />';
}
}
class B extends A {
function F($para1, $para2) {
parent::F($para1);
A::F($para1);
echo 'A2' . $para2;
}
}
$a = new A;
$b = new B;
$a->F('foo');
$b->F('bar', 'foo');
?>

Outputs A1foo<br />A1bar<br />A1bar<br />A2foo, which is expected. Class B's function F overwrites class A's. Same as the previous example.