Login |  Register 
I thought I knew all about PHP until I found this website!
Jen
 

Using static methods

Static methods allows methods to be accessed without having to iniate a class. This means that the method is accessed from a class and not a object instance. As the method isn't accessed from a object it means it has no access to any object variables or non-static methods and so can't use the pseudo variable $this furthermore static variables can't be accessed with the -> operator. Below is an example of a static methods.
class Helper
{
 private static $sitename = 'PHP Rocks! - ';

 public static function AddSiteName($pageName)
 {
  return self::$sitename . $pageName;
 }
}
Notice that in PHP you can't actually create a static class so a instance can still be made from this class. The helper function can be called like so
echo Helper::AddSiteName("Login");
//this echo's PHP Rocks! - Login
As you can see using static methods allows you to easily create classses such as helper classes, but static methods and variables must be used carefully because if they are overused they would remove the benifits of Object Orientation. Just as with normal variables you can also assign variables to static values, but these can only be literals or constants. So...
class Title
{
 public static MR = "Mr";
}


Title::MR = "Mrs";
echo Title::MR;

//echo's Mrs

No comments have been provided.
security image
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38