However, if less volatile data is created (say, stored in a database) as a result of the
instantiation and should be destroyed at the time of object destruction, you??™ll need to
create a custom destructor.
Static Class Members
Sometimes it??™s useful to create fields and methods that are not invoked by any particular
object but rather are pertinent to and are shared by all class instances. For example,
suppose that 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 the static scope:
class Visitor
{
private static $visitors = 0;
188 CHAPTER 6 ?– O BJECT-ORIENTED PHP
function __construct()
{
self::$visitors++;
}
static function getVisitors()
{
return self::$visitors;
}
}
/* Instantiate the Visitor class. */
$visits = new Visitor();
echo Visitor::getVisitors()."
";
/* Instantiate another Visitor class. */
$visits2 = new Visitor();
echo Visitor::getVisitors()."
";
?>
The results are as follows:
1
2
Because the $visitors field was declared as static, any changes made to its value
(in this case via the class constructor) are reflected across all instantiated objects.
Also note that static fields and methods are referred to using the self keyword and
class name, rather than via $this and arrow operators.
Pages:
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266