Why use PHP OOP over basic functions and when?

后端 未结 10 1908
深忆病人
深忆病人 2020-12-04 13:14

There are some posts about this matter, but I didn\'t clearly get when to use object-oriented coding and when to use programmatic functions in an include. Somebody also ment

相关标签:
10条回答
  • 2020-12-04 13:43

    The OOPs concept is used in PHP, so as to secure the code. As all the queries are written in function file instead of code file so no one can easily hack our code. So it is better to use classes in PHP instead of directly writing the queries.

    0 讨论(0)
  • 2020-12-04 13:46

    The accepted answer seems to have neglected to state that it is possible to call functions based on a variable name such as in the example herew:

    function drive($the_car){
        $the_car();
    }
    

    Admittedly there would need to be a function for each car in this instance but it's a lot more efficient than the suggested switch statement.


    Additional variables can be supplied easily as such:

    function operate($the_car,$action){
        $the_car($action);
    }
    
    function ferrari($action){
        switch($action){
            case 'drive':
                echo 'Driving';
                break;
    
            case 'stop':
                echo 'Stopped';
                break;
    
            default: return;
        }
    }
    
    
    operate('ferrari','drive');
    

    There is a switch statement here but it's to supply additional functionality that was not in the original example so it's in no way a contradiction.

    0 讨论(0)
  • 2020-12-04 13:48

    Lets say I have a big file with 50 functions, why will I want to call these in a class? and not by function_name(). Should I switch and create object which holds all of my functions?

    Moving to OOP should not been seen as a simple 'switch' in the way you describe above.

    OOP requires a completely different way of thinking about programming which involves rewiring your brain. As rewiring a brain doesn't happen overnight many people are unwilling to expose themselves to the required rewiring process. Unfortunately the rewiring is going to take an investment in time and effort: research, tutorials, trial and error.

    It really involves taking a step back and learning about the concepts behind OOP but the payback will be well worth it speaking as someone who went through this process in the pre www days.

    After you 'get it' and follow OOP best practices in your everyday you'll be telling others how your programming life has changed for the better.

    Once you really understand OOP you will have answered your own question.

    0 讨论(0)
  • 2020-12-04 13:52

    If you have 50 functions instead of 50 static methods into Utilities class, you "pollute" the global namespace.

    Using a class with 50 static methods, method names are local to your class.

    0 讨论(0)
提交回复
热议问题