Tutorial

Static Keyword in PHP

Static methos allow us to call the method of the class without creating an object of the class. So in that case we have to use scope resolution operator [code]::[/code] to call the static methods.

Declare Method as Static:

Static methods can be declared using keyword [code]static[/code]. Have look at below code bloc for the same:

[cc lang=”php”]
class new_class
{
// Static Methos Here
public static my_method()
{
// Code goes Here
}
}

[/cc]

Note: Static properties can not be accessed using arrow operator [code]->[/code].

Point to Keep in Mind

1) Calling non static method statically ( i.e. using :: ) will generate an E_STRICT level warning.
2) We can’t call static method using object creation, so [code]$this[/code] will not be available in the method declared as static. We have to use [code]self[/code] keyword to refer to the current class.

When to Use Static Method

Use of static method is totally depends on our need. But upto my knowledge I prefer to use static method if has same type of output. I will give a very good example for this.

In my earlier article on PHP Coding Tips, I have mentioned that static methods are 33% faster than normal methods.

As mentioned earlier, static method are useful if method have same type of output, just like returing the text box, text area, checkbox, radio button and other HTML elements.

Few days back I have written one class for printing the HTML elements, which have all static method declared. Because these functions will return just HTML element based on class, value and other given proerties.

Note: static methods are 33% faster than normal methods.

Let’s have look at the anatomy of that class:

[cc lang=”php”]

class aHTML
{
public static function text_box()
{
// Code goes Here
}

public static function text_area()
{
// Code goes Here
}

public static function check_box()
{
// Code goes Here
}

public static function radio_buttons()
{
// Code goes Here
}

public static function drop_down()
{
// Code goes Here
}

}
[/cc]

You can see that above class has all the methods defined as static. Let’s see how to call these methods.

[cc lang=”php”]

// For Printing the Text box
aHTML::text_box();

// For Printing the Text Area
aHTML::text_area();

//For Printing the Check Box
aHTML::check_box();

// Fpr Printing the Radio Button
aHTML::radio_buton();

// For Printing the Drop Down
aHTML::drop_down();

[/cc]

Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *