PHP Tutorial – 13 – Static and Constants
The static keyword is used to declare fields and methods that can be accessed without having to create an instance of the class. Static members exist in only one copy which belongs to the class itself, whereas instance members are created as new copies for each object.
class MyCircle { // Instance members (one per object) public $r = 10; function GetArea() {} // Static/class members (only one copy) static $pi = 3.14; static function ComputeArea($a) {} }
Static methods cannot use instance members since these methods are not part of any instance.
static function ComputeArea($a) { return $this->r; // error: a static method cannot // use an instance member }
They can however use static members by prefixing them with the self keyword followed by the scope resolution operator (::). The self keyword is an alias for the class name, so alternatively the actual name of the class can be used.
static function ComputeArea($a) { return self::$pi * $a * $a; // ok return MyCircle::$pi * $a * $a; // alternative }
Instance methods can in addition to instance members also access static members using the same syntax.
function GetArea() { return self::ComputeArea($this->$r); }
Similarly, to access static members from outside the class the name of the class is used followed by the scope resolution operator (::). The advantage of static members can be seen here in that they can be used without having to create an instance of the class. Methods should therefore be declared static if they perform a generic function independently of instance variables. Fields should be declared static if there is only need for a single instance of the variable.
echo MyCircle::$pi; // 3.14 echo MyCircle::ComputeArea(10); // 314
Constants
Another important field modifier is const, to make a field unchangeable. A constant field must be set to a constant value at the same time as it is declared. Unlike variables, constants don’t use the “$” parser token.
const PI = 3.14; echo PI; // 3.14
A constant field can’t be static or assigned an access level. They are accessed in the same way as static fields.
class MyCircle { const PI = 3.14; } echo MyCircle::PI; // 3.14
Variables outside of classes can also be made constant using the define function. The first argument to this function is the constant’s name and the second is its value. Just as constant fields they are used without the “$” token and their value cannot be modified.
define("MYCONSTANT", "Hello world"); echo MYCONSTANT; // Hello world
If you like this tutorial please +1 it:


![[Affiliate link] Total Training]( http://d3qzmfcxsyv953.cloudfront.net/images/pvt-affiliates/totaltraining.png)
![[Affiliate link] Lynda](http://d3qzmfcxsyv953.cloudfront.net/images/pvt-affiliates/lynda.png)

