开发者

simple functions or classes? [closed]

As it currently stands, this question is not a good fit for our Q&A form开发者_开发技巧at. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜