PHP: how to reuse code (oop)?

前端 未结 5 637
既然无缘
既然无缘 2021-01-14 00:34

I have studied in php oop and stocked in the concept of reusable code.

I have seen an example like

interface iTemplate
{
    public function setVar         


        
5条回答
  •  一整个雨季
    2021-01-14 00:53

    Code doesn't need to be OO to be reusable, although in many cases that helps.

    Code certainly doesn't need to use interfaces to be reusable, although again in some cases that will help.

    The key to writing reusable code is to write code that is clearly written, well-commented, uses consistent naming and calling conventions, and is more general than it strictly needs to be for the problem at hand.

    One of the simplest and most powerful techniques for writing reusable code in PHP is writing methods that accept either a variable number of arguments, or accept an associative array of parameters.

    Often, code that didn't start out "intending" to be reusable turns out to be something you'll want to reuse. Typically, code starts "inline" and then you discover you need to do exactly, or nearly exactly, the same thing in more than one place. When you find yourself copying and pasting code it's time to refactor it as a function.

    Similarly, when you find yourself wishing a function you had defined in file X would be really helpful in file Y, it's time to move it into a module.

    The best way to learn all this is by experience. Some people will tell you to architect this stuff from the beginning, and that's certainly a good idea if you have the insight and experience to do so, but it's just as valid to do so from the bottom up, and it's probably the best way to learn.

提交回复
热议问题