Do static methods equate to functions?

Asked

Viewed 95 times

5

In OOP we have static methods (do not depend on any instance variable). Citing examples:

class Somar {
    public static function soma($a,$b){
        return $a+$b;
    }
}
echo Somar::soma(20,30);

The equivalent of the method Static of the OOP programming are the functions of structured programming?

    function soma($a,$b){
        return $a+$b;
    }

 echo soma(20,30);

That is, the functions of structured programming are statics?

1 answer

3


Yes, functions function like static methods, the difference is that the method is encapsulated in a class, which avoids name conflicts that are more common in loose functions. Despite the term used, this is not even the truth encapsulation that we observe in OOP.

A function has global visibility and scope equal to the static method (although this may eventually have its visibility limited by another mechanism).

Technically a static method has nothing to do with OOP. Actually the fact that you use a class does not mean you are doing something OOP. To say it is OOP there must be other features in the code.

In fact the only difference between a static method and an instance method is that the instance one has a parameter hidden in the syntax called $this and this variable gives access to object members. If there was no syntax facility, an instance method:

function exemplo($p1, $p2) {}

It should be written like this:

function exemplo($this, $p1, $p2) {}

I put in the Github for future reference.

And would get the same result, at least from the point of view of access to the instance.

That is, in fact all methods are functions.

  • Python is a good example of this, where there is no Syntax Sugar for the context, which in the case of Python, is the "self".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.