PHP Constants, Static Methods and Properties

Jul 02, 2009 Author: LinuxAdmin

Along with PPP, PHP 5 also implements static methods and properties. Unlike regularmethods and properties, their static counterparts exist and are accessible as part of a class itself, as opposed to existing only within the scope of one of its instances. This allows you to treat classes as true containers of interrelated functions and data elements —which, in turn, is a very handy expedient to avoid naming conflicts. While PHP 4 allowed you to call any method of a class statically using the scope resolution operator :: (officially known as Paamayim Nekudotayim—Hebrew for “Double Colon”), PHP 5 introduces a stricter syntax that calls for the use of the static keyword to convey the use of properties and methods as such. You should keep in mind that PHP 5 is very strict about the use of static properties and methods. For example, calling static properties using object notation will result in a notice:

class foo {
static $bar = "bat";
static public function baz()
{
echo "Hello World";
}
}
$foo = new foo();
$foo->
baz();
echo $foo->bar;

This example will display:

foo::baz Notice: Undefined property: foo::$bar in PHPDocument1 on line 17

It is necessary for the static definition to follow the visibility definition; if no visibility definition is declared, the static method or property is considered public.


views 3566
  1. Add New Comment