I’ve seen a lot of classes with a SINGLE function in them. Why do they put a SINGLE function into class?
I use classes just to make things more clear, but about those who put a SINGLE function into class? Is there any reason for it?
I see no difference between these:
<?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);
and
<?php
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);
My thought was that $resource is the main reason, because it’s private:
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);
and therefore isn’t accessible to the global scope. But why isn’t a simple function used in this case?
Classes are not just “function containers”, they are there to represent an object, an entity. They are supposed to encapsulate the data required for the given entity with methods that work for it.
Sometimes there might be a class of object that only needs one method defined for it, but nevertheless it only belongs to that class of object.