PHP

Adding Static Data to Classes

The primary use of classes is to let us bind implementation and data into objects. However, situations arise where I want the ability to expose information about that class of objects without binding it to a particular object instance.

Class Constants

For example, in my preceding Product class, I are using two external constants (LOCAL_PRODUCT and NAVIGATION_PARTNER_PRODUCT) to represent possible sources for products. These pieces of information are directly related to a product, but they are not tied to a particular instance. I would like a way to associate these constants, and any new ones I defined to represent new suppliers or partner locations, with my Products class.

To solve this, PHP allows us to define public constants, which is done with the const keyword.

<?php
  class Product
  {
    const LOCAL_PRODUCT = 1;
    const NAVIGATION_PARTNER_PRODUCT = 2;
    // etc....
  }
?>

Constants are publically available, and can be used by anyone. They are not associated with any particular instance of this classthey are pieces of information associated with the class of objects or typeand you therefore cannot use the dereferencing operator (->) to access them. There are two contexts in which these constants can be used:

  • From outside the class To access a class constant outside of the class in which it is defined, you must first list the class name, and then use the scope resolution operator, which consists of two colons (::, also referred to as Paamayim Nekudotayim, which is Hebrew for "two colons"). Finally, you would use the constant name. Now, for my preceding example, I might see the creation of a new instance of the Product class as

    <?php
       $prod = new Product("101-44A55c",
                           "10 gallon gas tank",
                           "The 10 gallon gas tank is a ...",
                           14.95,
                           Product::LOCAL_PRODUCT);
    ?>
    

  • From within the class You can refer to the class name as in the previous code (in this case, Product), or you can use the new keyword, self, to tell PHP to look in the current class (or any of the classes whose functionality it extends) for such a constant. You can then use the scope resolution operator (::) and the constant name.

    <?php
      class Product
      {
         // etc.
        public function get_number_in_stock
        (
          $in_num_desired
        )
        {
          if ($this->location == self::LOCAL_PRODUCT)
          {
            // etc.
          }
          else
          {
            // etc.
          }
        }
      }
    ?>
    


by BrainBellupdated
Advertisement: