Questions And Answers

More Tutorials

PHP Classes and Objects

Classes and Objects are used to to make your code more efficient and less repetitive by grouping similar tasks. A class is used to define the actions and data structure used to build objects. The objects are then built using this predefined structure.

Class constants provide a mechanism for holding fixed values in a program. That is, they provide a way of giving a name (and associated compile-time checking) to a value like 3.14 or "Apple". Class constants can only be defined with the const keyword - the define function cannot be used in this context.

As an example, it may be convenient to have a shorthand representation for the value of π throughout a program. A class with const values provides a simple way to hold such values.
class MathValues {
 const PI = M_PI;
 const PHI = 1.61803;
$area = MathValues::PI * $radius * $radius;

Class constants may be accessed by using the double colon operator (so-called the scope resolution operator) on a class, much like static variables. Unlike static variables, however, class constants have their values fixed at compile time and cannot be reassigned to (e.g. MathValues::PI = 7 would produce a fatal error).

Class constants are also useful for defining things internal to a class that might need changing later (but do not change frequently enough to warrant storing in, say, a database). We can reference this internally using the self scope resolutor (which works in both instanced and static implementations)
class Labor {
 /** How long, in hours, does it take to build the item? */
 const LABOR_UNITS = 0.26;
 /** How much are we paying employees per hour? */
 const LABOR_COST = 12.75;
 public function getLaborCost($number_units) {
 return (self::LABOR_UNITS * self::LABOR_COST) * $number_units;

Class constants can only contain scalar values in versions < 5.6
As of PHP 5.6 we can use expressions with constants, meaning math statements and strings with concatenation are acceptable constants
class Labor {
 /** How much are we paying employees per hour? Hourly wages * hours taken to make */
 const LABOR_COSTS = 12.75 * 0.26;
 public function getLaborCost($number_units) {
 return self::LABOR_COSTS * $number_units;

As of PHP 7.0, constants declared with define may now contain arrays.
define("BAZ", array('baz'));

Class constants are useful for more than just storing mathematical concepts. For example, if preparing a pie, it might be convenient to have a single Pie class capable of taking different kinds of fruit.
class Pie {
 protected $fruit;
 public function __construct($fruit) {
 $this->fruit = $fruit;

We can then use the Pie class like so
$pie = new Pie("strawberry");

The problem that arises here is, when instantiating the Pie class, no guidance is provided as to the acceptable values. For example, when making a "boysenberry" pie, it might be misspelled "boisenberry". Furthermore, we might not support a plum pie. Instead, it would be useful to have a list of acceptable fruit types already defined somewhere it would make sense to look for them. Say a class named Fruit:
class Fruit {
 const APPLE = "apple";
 const STRAWBERRY = "strawberry";
 const BOYSENBERRY = "boysenberry";
$pie = new Pie(Fruit::STRAWBERRY);

Listing the acceptable values as class constants provides a valuable hint as to the acceptable values which a method accepts. It also ensures that misspellings cannot make it past the compiler. While new Pie('aple') and new Pie('apple') are both acceptable to the compiler, new Pie(Fruit::APLE) will produce a compiler error.
Finally, using class constants means that the actual value of the constant may be modified in a single place, and any code using the constant automatically has the effects of the modification.
Whilst the most common method to access a class constant is MyClass::CONSTANT_NAME, it may also be accessed by:
echo MyClass::CONSTANT;
$classname = "MyClass";
echo $classname::CONSTANT;

Class constants in PHP are conventionally named all in uppercase with underscores as word separators, although any valid label name may be used as a class constant name.
As of PHP 7.1, class constants may now be defined with different visibilities from the default public scope. This means that both protected and private constants can now be defined to prevent class constants from unnecessarily leaking into the public scope (see Method and Property Visibility ). For example:
class Something {
 const PUBLIC_CONST_A = 1;
public const PUBLIC_CONST_B = 2;
 protected const PROTECTED_CONST = 3;
 private const PRIVATE_CONST = 4;

define vs class constants
Although this is a valid construction:
function bar() { return 2; };
define('BAR', bar());

If you try to do the same with class constants, you'll get an error:
function bar() { return 2; };
class Foo {
 const BAR = bar(); // Error: Constant expression contains invalid operations

But you can do:
function bar() { return 2; };
define('BAR', bar());
class Foo {
 const BAR = BAR; // OK

For more information, see constants in the manual.
Using ::class to retrieve class's name
PHP 5.5 introduced the ::class syntax to retrieve the full class name, taking namespace scope and use statements into account.
namespace foo;
use bar\Bar;
echo json_encode(Bar::class); // "bar\\Bar"
echo json_encode(Foo::class); // "foo\\Foo"
echo json_encode(\Foo::class); // "Foo"

The above works even if the classes are not even defined (i.e. this code snippet works alone).
This syntax is useful for functions that require a class name. For example, it can be used with class_exists to check a class exists. No errors will be generated regardless of return value in this snippet:
class_exists(ThisClass\Will\NeverBe\Loaded::class, false);


In this page (written and validated by ) you learned about PHP Classes and Objects . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP Abstract Classes.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.