simple functions or classes? [closed]
I have a very simple question, but I'd like to know : When and why it's better to use simple functions, and when and why it's better to use classes?
I have simple answer:
Use classes when you need to treat with objects, especially when you need to persist data while calling functions.
Use simple function when you have just output from input, without accessing any other variables.
Example:
class Basket {
private $apples = 0;
public function fill() {
$this->apples = 100;
}
public function take($count) {
$this->apples -= $count;
}
public function applesInBasket() {
return $this->apples;
}
}
versus
/* simple */ function wrap_with_div($content) {
return "<div>$content</div>";
}
A function is a simple unit of processing that (can) take some input and (can) spit something out. A class is typically a representation of a piece of data, along with some functionality (methods) to process that data. But there is no strict separation. In more OO languages like Java, most (or all) types are classes. Even converting an integer to a string is done by calling a method on the integer. In PHP this is commonly done in a loose function.
Sometimes you got the choice. You can use the mysql* functions and pass resources to them on each call, or you can use the class variant, where the object is the resource, and the functions are methods (that omit that first parameter, of course).
In those cases, I would choose to use the object notation, but otherwise it's just a matter of taste.
It is always better to use classes. Functions pollute the global space.
精彩评论