0

I have 2 classes like

class A {
     public function B () {
         return 'b';
     }
}

class C extends A {
     public function D () {
         return 'd';
     }
}

I know that to use function b in class C I do,

class A {
     public function B () {
         return 'b';
     }
}

class C extends A {
     public function D () {
         $b = parent::B();
         return 'd';
     }
}

But what about when I initiate the object? Do I have to do (which works)

$c = new C();
$b = $c -> b();

Or do I still have to use this parent keyword?

I tried doing,

$c = new C();
$b = $c -> parent::B();

But it does not work.

Thanks

1
  • It's unclear what you are trying to do. It might be more clear if you used foo, bar, etc for method names instead of letters. Commented Jun 1, 2012 at 13:42

3 Answers 3

3

You do not need the parent keyword in the second example, since class C extends A, it inherits all of its member functions and variables. So, $c->b(); is perfectly valid. Here is a link to the documentation on the extends keyword, which states:

Often you need classes with similar variables and functions to another existing class. In fact, it is good practice to define a generic class which can be used in all your projects and adapt this class for the needs of each of your specific projects. To facilitate this, classes can be extensions of other classes. The extended or derived class has all variables and functions of the base class (this is called 'inheritance' despite the fact that nobody died) and what you add in the extended definition.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok call so if I use a function from a parent inside a childs class function use the parent keyword if not just use it as normal? Thanks, I did read the doc but you made it clearer :)
Correct, you'll only need parent inside the actual class definition (as in, inside one of the child class's functions). Otherwise, just call the function on an object of the child class.
1

When class C extends from A, you can use this to reach function B():

class C extends A {
     public function D () {
         $b = $this->B();
         return 'd';
     }
}

And likewise, from an instantiated class C you should call it as you mentioned using $c->B(). The parent:: construct is only meant to be used inside class methods; it can't be used outside of the class declaration.

Comments

0

Use the one that works.

When an instance inherits functions they are directly callable from that object. The caller does not need to be aware of whether b is some function of C or if c inherited it from another class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.