4

PHP でのクラスの拡張について質問があります。

PHPサイトで見た例では、メソッドに1行のコードしかありません...メソッドに大量のコードがある場合も同じですか??

これが基本クラスの場合:

class BaseClass {

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

}

次に、同じ方法を使用したいが、1 つまたは 2 つのことだけを変更したい場合、すべてのコードをコピーする必要がありますか?

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??
    }

}

これは私には少しDRYではないようです...

4

6 に答える 6

4

はい、これらの 1 つまたは 2 つのことがたまたま最初または最後にある場合を除きます。経由で親関数を呼び出すことができます

parent::WithWayTooMuchCode();

子/オーバーライドされたメソッドのどこにでも配置できます。

DRY と感じられない場合は、関数を小さなメソッドに分割することを検討してください。

于 2012-05-11T15:20:30.373 に答える
4

同じ方法を使用したいが、1 つまたは 2 つのことだけを変更したい場合、すべてのコードをコピーする必要がありますか?

いいえ、関数に追加し、その一部を削除しないと仮定すると、すべてのコードをコピーする必要はありません。

したがって、次のようになります。

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();
于 2012-05-11T15:20:44.410 に答える
2

親メソッドを実行し、コードを追加した後に、parent::WithWayTooMuchCode() を使用できます。次のようになります。

class MyOwnClass extends BaseClass {
     public function WithWayTooMuchCode {
      parent::WithWayTooMuchCode()

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

}
于 2012-05-11T15:24:50.430 に答える
1

親クラスで別々にやりたいことのために別の関数を書き留めてから、あなたのやり方で呼び出すことができます。

つまり、個別に行う必要があることを分離し、それらの機能を作成します。そして、それらを子クラスで個別に呼び出します。子クラスの最後の関数は、親クラスの関数とそれらの個別の関数を呼び出します。

于 2012-05-11T15:25:44.097 に答える
1

You have a few choices. Assuming;

class BaseClass {

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

You can do

class MyOwnClass extends BaseClass {
     public function AnotherFunction() {
         // put other code here
    }

}

This allows you to do MyOwnClass->AnotherFunction() and MyOwnClass->WithWayTooMuchCode()

or you could do

class MyOwnClass extends BaseClass {
     public function WithWayTooMuchCode() {
         // put new code here
    }

}

which will allow you to run MyOwnClass->WithWayTooMuchCode() and will ONLY run the "new code", not the "100 lines".

Finally you could do

class MyOwnClass extends BaseClass {
     public function WithWayTooMuchCode() {
         parent::WithWayTooMuchCode();
         // Do more processing
    }

}

which will allow you to run MyOwnClass->WithWayTooMuchCode() will run the "100 lines of code" AND the new code. You can put the parent before/after/during your new code, so you can tailor it as required

于 2012-05-11T15:27:47.350 に答える