PHP5 Tutorial – Defining Class Constants

January 1st, 2011 by Laeeq | 1 comment

In PHP4 the only constants that we would declare were global constants. In PHP5 it is possible to define a class level constant. These constants are specific to the class and hence don’t clutter the global level constant space.

To declare a constant in a class, PHP5 provides developers with a new keyword i.e. const; look at the example below:

class Customer {
const TYPES = “Anything”;
} 

echo “Types are : ” . Customer::TYPES;

 

In the above example, const is a keyword and TYPES is the name of the constant. Outside the class definition we echo the value of the constant by using the scope resolution operator (::) like this Customer::TYPES. Observe that we don’t need to create an object of the class to make use of the constant.

The next logical question is if we can create an object of the Customer class and using the scope resolution operator access the constant. The answer is no; reason – because a constant belongs to the class definition scope and not to an object.

Example of accessing Constants within a function

class Customer {
const TYPES = “Anything”; 

public function showConstant() {
echo “Echo from showConstant() : ” . Customer::TYPES;
}

}

$c = new Customer();
$c->showConstant();
Output:
Echo from showConstant() : Anything

 

Few important points on Constants

Variables defined as constants cannot be changed.

Only a string or numeric value can be assigned to a constant.

Arrays, Objects & Expressions cannot be assigned to a constant.

A class constant can only be accessed via the scope resolution operator (::) executed on the class name.

A class constant cannot have access specifiers assigned to it (private, public & protected)

 

 

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • Find Time Between Two Dates in PHP
  • Creating Objects in PHP5 Class
  • PHP5 Tutorial – Definition of a class attribute
  • PHP5 Tutorial – Creating a PHP5 Destructor
  • PHP5 Tutorial- Definition of Constructor
  • PHP5 Tutorial – __clone() method
  • PHP5 Tutorial – magic method
  • PHP5 Tutorial – Magic Methods – __autoload() method
  • PHP5 Tutorial – magic method __call()
  • PHP5 Tutorial – Magic Methods – __isset() and __unset()
  • PHP5 Tutorial – get()) and __set() magic method
  • PHP5 Tutorial – __toString() method
  • PHP5 Tutorial – Polymorphism
  • PHP5 Tutorial – abstract class and interface
  • PHP5 Tutorial- Inheritance
  • PHP5 Tutorial – exception handling
  • PHP5 Tutorial – Final Class and Final Method
  • PHP5 Tutorial – Static Data Members and Methods
  • PHP5 Tutorial – instanceOf Operator
  • PHP5 Tutorial – $this variable
  •  

     

    1. mario bros
      October 14th, 2012 at 13:17 | #1

      Excellent article! We will be linking to this
      great content on our site. Keep up the good writing.

    1. No trackbacks yet.