Static methods in OOP

13,232

Solution 1

Static functions are helpful as they do not rely on an instantiated member of whatever class they are attached to.

Static functions can provide functionality related to an a particular class without requiring the programmer to first create an instance of that class.

See this comparison:

class Numbers
{
    public int Add(int x, int y)
    {
        return x + y;
    }

    public static int AddNumbers(int x, int y)
    {
        return x + y;
    }
}

class Main
{
    //in this first case, we use the non-static version of the Add function
    int z1 = (new Numbers()).Add(2, 4);

    //in the second case, we use the static one
    int z2 = Numbers.AddNumbers(3, 5);
}

Solution 2

Technically, answers above are correct. But the examples are not correct from the OOP point of view.

For example you have a class like this:

class Zip
{
    public static function zipFile($fileName)
    {
        //
    }

    public static function unzipFile($fileName)
    {
        //
    }
}

The truth is that there is nothing object-oriented here. You just defined two functions which you need to call using the fancy syntax like Zip::zipFile($myFile) instead of just zipFile($myFile).

You don't create any objects here and the Zip class is only used as a namespace.

So in this case it is better to just define these functions outside of class, as regular functions. There are namespaces in php since version 5.3, you can use them if you want to group your functions.

With the OOP approach, your class would look like this:

class ZipArchive
{
    private $_archiveFileName;
    private $_files;

    public function __construct($archiveFileName) {
        $this->_archiveFileName = $archiveFileName;
        $this->_files = [];
    }

    public function add($fileName)
    {
        $this->_files[] = $fileName;
        return $this; // allows to chain calls
    }

    public function zip()
    {
        // zip the files into archive specified
        // by $_archiveFileName
    }
}

And then you can use it like this:

$archive = new ZipArchive('path/to/archive.zip');
$archive->add('file1')->add('file2')->zip();

What is more important, you can now use the zip functionality in an OOP way.

For example, you can have a base class Archive and sub-classes like ZipArchive, TarGzArchive, etc.

Now, you can create an instance of the specific sub-class and pass it to other code which will not even know if files are going to be zip-ped or tag.gz-ipped. For example:

if ($config['archive_type'] === 'targz') {
   // use tar.gz if specified
   $archive = new TarGzArchive($path);
} else { 
   // use zip by default
   $archive = new ZipArchive($path);
}
$backup = new Backup($archive /*, other params*/);
$backup->run();

Now the $backup object will use the specified archive type. Internally it doesn't know and doesn't care how exactly files will be archived. You can even have a CopyArchive class which will simply copy files to another location.

It is easy to do it this way because your archive support is written in OOP way. You have small object responsible for specific things, you create and combine them and get the result you want.

And if you just have a bunch of static methods instead of real class, you will be forced to write the procedural-style code.

So I would not recommend to use static methods to implement actual features of your application.

Static methods may be helpful to support logging, debugging, testing and similar things. Like if you want to count number of objects created, you can use class-level static counter, increment it in the constructor and you can have a static method which reads the counter and prints it or writes to the log file.

Share:
13,232
user1542422
Author by

user1542422

Updated on June 04, 2022

Comments

  • user1542422
    user1542422 about 2 years

    I've always known what static methods are by definition, but I've always avoided using them at school because I was afraid of what I didn't know.

    I already understand that you can use it as a counter throughout your entire project.

    Now that I am interning I want to know when exactly static methods are used. From my observation so far, static classes/methods are used when it contains a lot of functions that will be used in many different classes and itself doesn't contain too many critical local variables within the class where it is not necessary to create an instant of it.

    So as an example, you can have a static class called Zip that zips and unzips files and provide it to many different classes for them to do whatever with it.

    Am I right? Do I have the right idea? I'm pretty sure there are many ways to use it.