Saturday, October 25, 2014

Instance vs. Static Methods

/*

I must confess. I'm fairly new to object-oriented programming. My first programming language was BASIC—as procedural as you can get. I stuck with that until HTML came along and went over in that space. Still procedural. I could write if/else blocks all day long.

But the last couple of years, my world has expanded. I began looking at objected-oriented design. Lots of jargon (which I won't go into here), and lots of new concepts and design patterns. I realized that PHP, my server-side language of choice, has a fully integrated object-oriented model built into it.

Then I started learning about classes and objects, methods and attributes. I picked it up, but I had one area that I continually went in circles about:
:: vs. ->
Now I get it. The first (::) is the way to call a static method in a class. The second (->) is the way to call an instance method of a class. Okay...........so which is which?

As the name implies, an instance method can only be called when the class has been instantiated. When I heard that, it was a like a "Duh" moment for me. Okay, so I can call them like this:
require_once 'Foo.php';$foo = new Foo();$instance = $foo->instance();
Seems easy enough. Now what about the double colon? (Fun fact: in PHP, it's referred to as "T_PAAMAYIM_NEKUDOTAYIM", but its jargon name is the "scope resolution operator") Well, we can call static methods in a class by using the double colon, and we don't have to instantiate the class to use them. If a method is public, static, and the class file is included, we don't have to instantiate it to use it. All we do is add the keyword "static" when we're defining our method, and voilĂ , we have access:
require_once 'Foo.php';$static = Foo::notInstance();
Quick sidebar: There's more to using the :: than this with inheritance and accessing other methods inside of a class, but at its heart, this is all we need to get access to the static methods in the class.
How you define your methods and attributes is up to you, but I tend to put helper methods in a static role, and put my more core methods in an instance role. I've heard it's common to use static functions in local development environments (three lines of code vs. two is the only marginal benefit I see in doing that), but again, it's up to you.

*/