我已经看到很多类中都有一个单一的函数。为什么他们把一个单一的函数放在课堂上呢?
我使用类只是为了让事情变得更清楚,但是对于那些将单个函数放入类的人呢?有什么理由吗?
我看不出这两者之间有什么不同:
<?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-06-20 21:02:50
类不仅仅是“函数容器”,它们是用来表示一个对象、一个实体的。它们应该用为其工作的方法封装给定实体所需的数据。
有时,可能有一个对象类只需要为其定义一个方法,但它只属于该对象类。
发布于 2011-06-20 21:05:50
我主要从事嵌入式编程,很少使用类。但是一个函数类可能被用来-
(encapsulation).
发布于 2011-06-20 21:22:55
为什么某些函数中只有一行代码?因为这是唯一需要的。现在,您可以调用该函数,而不是到处重复一行代码。如果这一行代码需要调整,它只需要在一个地方发生。这是利用过程封装的优势。
你的短训班也是如此。现在您可以利用类所能做的一切,特别是继承和多态,比如SVGImage extends Image和重写方法resize。
没有实现必要功能所需的最小行数。
https://stackoverflow.com/questions/6417446
复制相似问题