Jump to Navigation

034 - OOP Static Class Members

You are writing a class that tracks the number of Web page visitors. You wouldn't want the visitor count to
reset to zero every time the class is instantiated, and therefore you would set the field to be of static scope.
Also static fields and methods are referred to using the self keyword and class name, rather than via this
and arrow operators.

Example:

class Visitor
{
private static $visitor =0;

function __ construct()
{
self::$visitors++;
}

static function getVisitors()
{
return self::$visitors;
}

}

/* Instantiate the Visitor class. */
$visits = new Visitor();

echo Visitor::getVisitors() . "<br / >";

/* Instantiate another Visitor class. */
$visits2 = new Visitor();

echo Visitor::getVisitors() . "<br />";

--------------------------------------------------------
1
2

PHP:


Main menu 2

Story | by Dr. Radut