Constants,
Static Methods and Properties
Along with PPP, PHP 5 also
implements static methods and properties. Unlike regular methods 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.
Class
Constants
Class constants work in the same way
as regular constants, except they are scoped within a class. Class constants
are public, and accessible from all scopes; for example, the following script
will output Hello World:
class foo {
const BAR =
"Hello World";
}
echo foo::BAR;
Class constants have several
advantages over traditional constants: since they are
encapsulated in a class, they make
for much cleaner code, and they are significantly
faster than those declared with the
define() construct.
0 Comment to " PHP Constants, Static Methods and Properties "
Post a Comment