When to use a Class vs. Function in PHP

后端 未结 6 1974
长发绾君心
长发绾君心 2020-12-02 08:59

The lightbulb has yet to go on for this...

I\'d really love an easy to understand explanation of the advantage to using a class in php over just using functions. <

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 09:37

    Using classes is a good way for grouping your functions.

    The difference lies in the usage of the programming paradigm. Classes are necessary in O.O.P. but are not necessary in the Procedural paradigm. In the Procedural paradigm you can group functions in a file, which can be seen as a module.

    --- edit ---

    You could use procedural paradigm. Classes are not really needed in this paradigm.

    function miniCal($string_1, $string_2){
    //do something   
    }
    
    //invoke function
    miniCal('arrayVars1', 'var2');
    

    You could use OOP paradigm. Classes are needed.

    class Calculation {
    
    public static function miniCal($string_1, $string_2){
        //do something   
        }
    }
    
    //invoke function
    Calculation::miniCal('arrayVars1', 'var2');
    

    Conclusion

    Both paradigma's work, but the OOP example from the above is using a Calculations object which contains all calculations methods (functions). The Calculations object groups calculation functions, thus keeping them in one place.

    The O.O.P. paradigm in this example obeys to a principles called "Solid responsibility". The idea behind this is to keep the code elegant, maintainable and readable.

提交回复
热议问题