jump to navigation

PHP Static Method the basics October 10, 2010

Posted by Tournas Dimitrios in PHP.

My previous article introduced the concept of OOP with PHP .Lets get dive a little deeper , and focusing on “static methods” .

This article is different because it deals with only the creation of a static method. Before we continue, we will insure we know the difference between a non-static class method and a static method.

Non-Static Method Static Method
1 Requires creating a class object Can be called without creating a class object
2 Can call on other static methods and variables Can only call on static methods and function

The real world example of the differences between a non static method and static method can be an old full sized computer tower. In the static method point of view, assume you only want to use the computer tower as a foot rest when you sit at your desk. For this, you do not need to turn on the computer (create a class object). This does not require you to load you operating system (no instantiating of class variables required). But, you can still kick up your feet. However, because you did not turn on your computer, you will be unable to access non-static methods (can only call on static method methods).

In the non-static method point of view, if you want the operation system, you would need to turn on the computer (create class object). What this does is load your operating system (instantiate class variables) so you can finally login to your computer (method of the class). Additionally, with the computer on, we can still kick our feet on the tower (can call both static and non static function).

Now how do we create a function with static methods in PHP? When we write the static method, we must use the keyword static. This method we create will always return true and is created in the common class.

class common {
   public static function myStaticFunction()
      return true;

Now that we have created the static function, we can call on the static method with the following snippet of code. The first term “common” is the name of the class. This is followed by two colons (::) followed by the method name.

$value = common::myStaticFunction();

And there we have it! We have successfully created and used our static method. To see the official PHP article on static, go to http://php.net/manual/en/language.oop5.static.php


No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s