Friday, 18 Jan 2008 7:00PM EST
PHP Classes Part 3: Static Keywords, Constants and the Scope Resolution Operator
From time to time in your PHP class adventures you may need to declare a variable as static or define a constant value. If you've ever used these objects in a language similar in syntax (i.e. C++), this should all be familiar, but if not, this tutorial will give you all the information to begin employing these important concepts. Those of you who are true PHP newbs, might want to check out the first 2 parts of this series; The Basics of PHP Classes and The Basics of PHP Abstract Classes.Let's start by defining static varibles and constants. A constant is a value that you define in your class which must be equal to a constant expression. This means that you constant can be set to any string or number, but not to the value of a variable, the result of a function call or the result of a mathematical expression. The constant will be inherited by any and all instances of that class which you create. The static keyword, on the other hand, can be applied to any member or method of a class. These members and methods are no different than any other, except that they can be accessed without creating an instance of that class.
Defining a constant is simple. You precede the name of your constant with the const keyword and set it equal to whatever your constant value is. To access the value of your constant, you'll need to use the scope resolution operator (::) preceded by either self (from within the class) or the name of the class (from outside of the class).
<?php
class MyClass {
const someconstant = 'value of my constant';
public function printConst() {
echo self::someconstant;
}
}
// Print constant value without a class instance
echo MyClass::someconstant;
/*** In PHP5.3+ ***/
//Print constant value without a class instance while
//storing the class name in a variable
$className = "MyClass";
echo $className->printConst();
//Print constant value through an instance of the class
$classInstance = new MyClass();
$classInstance->printConst();
//or
echo $classInstance::someconstant;
?>
<?php
class ParentClass {
public static $staticVar = 'some value';
public function returnStaticVal() {
return self::$staticVar;
}
}
class ChildClass extends ParentClass {
public function returnStaticFromChild() {
return parent::$staticVar;
}
}
// Print static value without a class instance
print ParentClass::$my_static;
// Print static value with a class instance
$classInstance = new ParentClass();
print $classInstance->returnStaticVal();
//Print static value without a class instance while
//storing the class name in a variable
$className = 'ParentClass';
print $className::$staticVar;
// Print static value from a child class instance
print Childclass::$staticVar;
$childInstance = new ChildClass();
print $childInstance->returnStaticFromChild();
?>
















3 Comments So Far