我已经看到很多类中都有一个单一的函数。为什么他们把一个单一的函数放在课堂上呢?
我使用类只是为了让事情变得更清楚,但是对于那些将单个函数放入类的人呢?有什么理由吗?
我看不出这两者之间有什么不同:
<?php
class Image {
    private $resource;
    function resize($width, $height) {
        $resized = imagecreatetruecolor($width, $height);
        imagecopyresampled($resized, $this->resource, 0, 0, 0, 0, $width, $height, imagesx($this->resource), imagesy($this->resource));
        $this->resource = $resized;
    }
}
$image = new Image();
$image->resource = "./someimage.jpg";
$image->resize(320, 240);和
    function resize($width, $height) {
        $resource = "./someimage.jpg";    
        $resized = imagecreatetruecolor($width, $height);
        imagecopyresampled($resized, $resource, 0, 0, 0, 0, $width, $height, imagesx($resource), imagesy($resource));
        $resource = $resized;
        return $resource;
    }
resize(320, 240);我的想法是,$resource是主要原因,因为它是隐私的:
class Image {
    private $resource;
    function resize($width, $height) {
        $resized = imagecreatetruecolor($width, $height);
        imagecopyresampled($resized, $this->resource, 0, 0, 0, 0, $width, $height, imagesx($this->resource), imagesy($this->resource));
        $this->resource = $resized;
    }
}
$image->resize(320, 240);因此无法访问全局范围。但是为什么在这种情况下不使用一个简单的函数呢?
发布于 2011-10-11 09:13:45
除了上面给出的关于为什么将单个方法包装到类中的一些重要原因外,这里还有一个原因:
在C++中,如果您想为一个方法提供一个接口,就必须定义一个调用。
例如:
class CallBackClient
{
   public:
   // A callback function. 
  virtual s32 callback( int param1, int param2 ) = 0;
};每个想要提供自己的回调实现的客户端都需要扩展到该类。
Java为可以“实现”的接口提供了一个直接表示法。
https://stackoverflow.com/questions/6417446
复制相似问题