开发者

When to use a Class vs. Function in PHP

开发者 https://www.devze.com 2022-12-17 02:24 出处:网络
The lightbulb has yet to go on for this... I\'d really love an easy to understand explanation of the advantage 开发者_JS百科to using a class in php over just using functions.

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

I'd really love an easy to understand explanation of the advantage 开发者_JS百科to using a class in php over just using functions.

Here's a simple example of the thought I'm having now and am wondering if a class is more efficient:

Say I have a mini calendar widget that I've built in php. I'm thinking about calling the function miniCal('arrayVars1', 'var2'). But I might do it twice on that page. Do use fewer resources by using a class here, create new instances of it?

What tree should I be barking up here, because I feel like right now the tree is a brick wall...


Classes are used for representing data as objects. If you're representing something like a user's data, or an auction bid, creating a User object or AuctionBid object makes it easier to keep that data together, pass it around in your code, and make it more easily understandable to readers. These classes would have attributes (data fields like numbers, strings, or other objects) as well as methods (functions that you can operate on any class).

Classes don't usually offer any benefits in terms of performance, but they very rarely have any negative effects either. Their real benefit is in making the code clearer.

I recommend you read the PHP5 Object-Oriented Programming guide and the Wikipedia OOP entry.


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.


Using classes is a good way for grouping your functions. The question is which functions should belong together? You've probably heard of 'Low Coupling, High Cohesion'. Let's focus on High Cohesion in this answer.

Let's say you a couple of functions, and they perform some calculations which are related to each other. Like this:

function plus1($a){
    return $a + 1;
}

function plus2($a, $b){
    return $a + $b;
}

function plus3($a, $b, $c){
    return $a + $b + $c;
}

function plus4($a, $b, $c, $d){
    return $a + $b + $c + $d;
} 

It would make sense to group functions which are related to each other.

class PlusCalculator {

    public function plus1($a){
        return $a + 1;
    }
    
    public function plus2($a, $b){
        return $a + $b;
    }
    
    public function plus3($a, $b, $c){
        return $a + $b + $c;
    }
    
    public function plus4($a, $b, $c, $d){
        return $a + $b + $c + $d;
    }
}

So when should you use a class instead of a function? The answer lies in the usage of the programming paradigm and style. Classes are necessary in O.O.P. but are (less) necessary in the Procedural paradigm. In purely functional programming languages you don't have classes.

But in O.O.P. languages, I would say group functions to a class when they are coherent.


Functions are the meat of your application and classes are more like the plate. It's messy to eat meat without a plate. But if you don't have any meat, you don't have a meal.

If you have 500 functions in your applications, you're probably going to want to group at least half of them into larger collections for ease of access. You can devise common naming conventions ("Encryption_Encrypt", "Encycryption_Decrypt", etc.)...but classes are just easier. If you only have 12 functions in your application, you could probably survive with only 1 or classes, if any.

I don't often need to store data/properties in classes. I tend to store those in the database. So I haven't take advantage of that aspect of classes very often.

Classes also allow polymorphism, which can be helpful. If you have several classes that are extremely similar, or several variations on a class, you can save code...without having to construct some multi-purpose, Frankenstein-like class.


I have a list of places you would use OOP-Style Classes in my answer to this question: https://stackoverflow.com/questions/2035449/why-is-oop-hard-for-me/2035482#2035482

Basically, whenever you want to represent an object that has things in it. Like a database variable that has a connection in it that is unique. So I would store that so I can make sure that the mysql_query uses the correct connection everytime:

class MySQL extends Database
{
    public function connect($host, $user, $pass, $database)
    {        
        $this->connection = mysql_connect($host, $user, $pass);
        $this->select_db($database);
    }

    public function query($query)
    {
        return mysql_query($query, $this->connection);
    }

    public function select_db($database)
    {
        mysql_select_db($database);
    }    
}

Or maybe you want to build a Form, you could make a form object that contains a list of inputs and such that you want to be inside the form when you decide to display it:

class Form
{
    protected $inputs = array();
    public function makeInput($type, $name)
    {
         echo '<input type="'.$type.'" name="'.$name.'">';
    }

    public function addInput($type, $name)
    {
         $this->inputs[] = array("type" => $type,
                "name" => $name);
    }

    public function run()
   {
       foreach($this->inputs as $array)
       { 
          $this->makeInput($array['type'], $array['name'];
       }
    }
}

$form = new form();

$this->addInput("text", "username");
$this->addInput("text", "password");

Or as someone else suggested, a person:

class Person{

    public $name;
    public $job_title;
    // ... etc....

}

All are reasons to create classes as they represent something that has properties like a name or a job title, and may have methods, such as displaying a form.


Basically Both Do same work but by using classes you can manage your code in easier way, One more thing if we use class then we have to create object for calling functions define in it, while if we create functions directly then we don't need to create object.

0

精彩评论

暂无评论...
验证码 换一张
取 消