Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP extending a class

Tags:

oop

php

I have a question about extending a class in PHP.

The examples I see on the php site just have 1 line of code in the method...is it the same if the method has tons of code??

If this is the base class:

class BaseClass {

    public function WithWayTooMuchCode {
      // like 100 lines of code here
    }

}

Then do I have to copy all the code over if I want to use the same method, but change only 1 or 2 things?

class MyOwnClass extends BaseClass {
     public function WithWayTooMuchCode {
      // like 100 lines of code here

     // do I have to copy all of the other code and then add my code??
    }

}

This seems a little not DRY to me...

like image 746
redconservatory Avatar asked Dec 16 '22 00:12

redconservatory


2 Answers

Yes, unless those 1 or 2 things happen to be at the beginning or the end. You can call the parent function via

parent::WithWayTooMuchCode();

Which you can place anywhere in the child/overridden method.

If it doesn't feel DRY, consider splitting the function into smaller methods.

like image 185
mpen Avatar answered Jan 01 '23 07:01

mpen


do I have to copy all the code over if I want to use the same method, but change only 1 or 2 things?

No, you don't have to copy all of the code, assuming you're adding to the function and not removing pieces of it.

so it follows:

class BaseClass {

    public function WithWayTooMuchCode {
      // like 100 lines of code here
    }

}

class MyOwnClass extends BaseClass {

    public function WithWayTooMuchCode { 
        parent::WithWayTooMuchCode();
        //additionally, do something else
    }

}

$moc = new MyOwnClass();
$moc->WithWayTooMuchCode();
like image 33
Kristian Avatar answered Jan 01 '23 06:01

Kristian