Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Static vs Instance Method

Tags:

oop

php

I'm a little bit confused as I don't have much experience in OOP in PHP. I always hear that using instance methods is a better practice than using static methods, why is that?

I need a deep answer with an explanation, please.

For example why this below should be done with the instance method?

Controller:

public function getProperty($id){
        $property = Property::getProperty($id);
        return $property;
}

Model:

public static function getProperty($id){
        //$query = DB::table('properties')...
        //Some Code;
        return $query;         
}

I'm reading about setter/getter, instance vs static and etc. But I need a complete answer to understand the how and why of things.

like image 827
Makis Avatar asked May 22 '15 17:05

Makis


People also ask

What is the difference between static and instance methods?

Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.

When should I use static methods in PHP?

When to define static methods ? The static keyword is used in the context of variables and methods that are common to all the objects of the class. Therefore, any logic which can be shared among multiple instances of a class should be extracted and put inside the static method.

What is difference between static method and non static method in PHP?

Static class contains static variables and static methods whereas instantiated class contains non-static variables and non-static methods. Programs having static classes are hard to test and to extend while programs with non-static classes provide easy testing and extending property.

Which one is faster static method or instance method?

They are faster — Static methods are slightly faster than instance methods because in instance methods, you are also working with an implicit this parameter. Eliminating that parameter gives a slight performance boost in most programming languages.


1 Answers

In general, as you've already stated, instance methods are the better practice. That isn't to say that static methods are downright evil, they simply have a different and unique purpose.

It is important to note that when dealing with instance methods you are working with an object whereas with static methods you are working with a class. When using static methods you will not have access to any of your non-static properties that would normally be available with an instance.

Take the following code as an example:

class Foo
{
    private $bar;
    private static $tavern;

    public function changeBar($value)
    {
        $this->bar = $value;
    }

    public function getBar()
    {
        return $this->bar;
    }

    public static function changeTavern($value)
    {
        self::$tavern = $value;
    }

    public static function getTavern()
    {
        return self::$tavern;
    }
}

Class Foo has a static property $tavern and a non-static property $bar.

If an instance of Foo is created then all properties and methods are available to that object.

If Foo is referenced statically then only the $tavern property, changeTavern() method and getTavern() method are available to the class.

Let's look at the following code:

$foo = new Foo();
$foo->changeBar('Tipsy Turvy');
echo $foo->getBar(); // prints Tipsy Turvy

Since $foo is an instance of Foo, it has access to the entire class. Calling changeBar() will modify the $bar property. To change the $bar property directly from a static method will trigger an error since $bar is available to the object and not the class.

// Calling this method would trigger an error
public static function changeBar($value)
{
    $this->bar = $value; // PHP will crash and burn if you try this.
}

If you want to access class properties from static methods those properties must also be declared static. This will work in the context of the class above. You'll also note that an instance of Foo has no problem reading static properties.

Foo::changeTavern('Stumble Inn');
echo Foo::getTavern(); // prints Stumble Inn
echo $foo->getTavern(); // also prints Stumble Inn

Another thing to remember about static code is that it doesn't behave like an instance. When the first instance of Foo was built both properties $bar and $tavern had no value. If you were to create another instance of Foo you would find that only one of those properties no longer contains a value. (I'm sure by now you can guess which one.)

$anotherFoo = new Foo();
echo $anotherFoo->getBar(); // prints nothing
echo $anotherFoo->getTavern(); // prints Stumble Inn
echo Foo::getTavern(); // prints Stumble Inn

So again, static code means you are working directly with a class - instances mean you are working with an object. It is important to note that any type of class you write that intends to have some kind of state to it should be used as an instance.

Static classes can be a little difficult to debug and test. Testing can be problematic because static properties don't change when you create a new instance. Debugging can also be difficult since the value of a static property is the same across all instances of an class. Make a change in one and you will make that change in all of them. Tracking down which instance made the change is a pain.

Speaking metaphorically, use static classes like sugar - sparingly and only when necessary.

Hope that helps shed some light on the topic.

like image 97
Crackertastic Avatar answered Sep 26 '22 13:09

Crackertastic