PHP

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.

:: vs. ->, self vs. $this

For people confused about the difference between :: and -> or self and $this, I present the following rules:

  • If the variable or method being referenced is declared as const or static, then you must use the :: operator.

  • If the variable or method being referenced is not declared as const or static, then you must use the -> operator.

  • If you are accessing a const or static variable or method from within a class, then you must use the self-reference self.

  • If you are accessing a variable or method from within a class that is not const or static, then you must use the self-referencing variable $this.


by BrainBellupdated
Advertisement: