Stephen
Stephen

Reputation: 2550

Class inheritance - Calling properties and/or methods not in the parent class

I'm trying to understand class inheritance.

Suppose I have the following code (PHP):

class A {
     public function fire() {
        echo "Fire!";
     } 
}

class B extends A {
     public function water() {
        echo "Water!";
     }
}

class C extends B {
     public function lightning() {
         echo "Lightning!";
     }
}

$cObject = new C();

$cObject->fire();  

My questions are

Upvotes: 1

Views: 176

Answers (2)

reuscam
reuscam

Reputation: 1841

1) Class 'B' is an 'A'. Class 'C' is a 'B', therefor, 'C' is an 'A'. Everything that 'B' has rights and privileges to in 'A', 'C' has as well. C++ has a concept of private inheritance that gets a little funky here, but that's the general idea. As said in the other answer, inheritance will go as far as the chain is defined.

2) I think you meant to ask "What is a function called that is not defined in derived class, but instead in the base class. This type of function is called a virtual function. From what I understand, every class function in PHP is a virtual function and can be overridden (reimplemented in a derived class) unless it is declared as final.

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 157947

I'm trying to find out how many levels deep inheritance will go.

infinetely, if you want. no limits

Is there a term for calling a property or method that does not exist in the current object instance, but this property or method exists in a parent or ancestor class?

For class variables: no. For class methods: yes. declare them as private:

class A {
    private function test() {
        echo 'test';
    }
}

class B extends A {
    public function __construct() {
        $this->test();
    }
}

$b = new B();

Output:

Fatal error: Call to private method A::test() from context 'B' in /home/thorsten/a.php on line 14

Upvotes: 2

Related Questions