[Previous] [Contents] [Next]


Static Methods


There will also come a time when you want to associate methods with your type that do not necessarily operate on a specific instance but are broad operations related to that type. For example, I might want to define a method on the Product class that creates a number of Product objects. This would let us put most of the implementation of products into one class!

I declare a static method by declaring a normal function with the static keyword included:

<?php

  class Product
  {
    // etc....

    public static function get_matching_products($in_keyword)
    {
      // go to the db and get all the products matching
      // the keyword given ... this would probably return
      // an array of Product objects.
    }
  }

?>

I have now set up my Product class so that various pages in my web application can call a method to get an array of Product objects as follows:

<?php

  $prods = Product::get_matching_products($keyword);

?>

Static methods are allowed to have a visibility modifier of private or protected to restrict access to information.


[Previous] [Contents] [Next]