PHP Properties

Properties of a class can be defined as 'private', 'protected' or 'public'. If none of these is specified or 'var' is specified then 'public' is assumed. Properties can be initialised when they are declared but such initialisation must use a constant value that can be determined prior to the script starting to run. If you wish to assign a value from another variable in your script then it must be done as a separate assignment after the property is declared.

Each object created from a class will have its own copy of all of the properties unless the properties are defined as 'static'. A static property exists independently of any objects created from the class and can be referenced even if no objects of that class type exist. While ordinary properties are referenced from within the class using $this->propertyName and from outside the class using $objectName->propertyName, static properties are usually referenced using ClassName::propertyName although self::propertyName can also be used from within the class itself.

Properties can also be defined as 'const' which means that the property will always contain the same value and changing the value of the property is not allowed. The value of the property must be assigned when it is declared in this instance. Constants are always public and static. By convention constant names are specified as all uppercase so as to make it clearer to anyone reading the code that it is in fact a constant.

Some examples of property declarations are:

public $myvar1 = 'myConstant';
private $var2 = array(true, false);
public static $my_static = 'foo';
const CONSTANT = 'constant value';


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow