When to use a Class vs. Function in PHP

后端 未结 6 1976
长发绾君心
长发绾君心 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条回答
  •  没有蜡笔的小新
    2020-12-02 09:47

    A common thing to do since PHP5 was to create classes that act as libraries. This gives you the benefit of organizing your functionality and taking advantage of class features like __autoload();

    For example, imagine you have two functions for encrypting and decrypting data. You can wrap them in a class (let's call it Encryption) and make them static functions. You can then use the functions like this (notice no initialization is needed (i.e. $obj = new Encryption)):

    $encrypted_text = Encryption::encrypt($string);
    

    and

    $decrypted_text = Encryption::decrypt($string);
    

    The benefits of this are:

    1. Your encryption functionality is grouped together and organized. You, and anyone maintaining the code, know where to find your encryption functionality.
    2. This is very clear and easy to read. Good for maintainability.
    3. You can use __autoload() to include the class for you automatically. This means you can use it like it was a built in function.
    4. Because it is contained in its own class and own file it is reusable and can easily be ported to new projects.

提交回复
热议问题