PHP/Class/static properties
Содержание
static class members
<?php
class visitors
{
private static $visitors = 0;
function __construct(){
self::$visitors++;
}
static function getVisitors(){
return self::$visitors;
}
}
$visits = new visitors();
echo visitors::getVisitors()."<br />";
$visits2 = new visitors();
echo visitors::getVisitors()."<br />";
?>
static class properties
<?php
class visitors
{
private static $visitors = 0;
function __construct()
{
self::$visitors++;
}
static function getVisitors()
{
return self::$visitors;
}
}
$visits = new visitors();
echo visitors::getVisitors()."<br />";
$visits2 = new visitors();
echo visitors::getVisitors()."<br />";
?>
Use the static modifier to change a member or method
<?php
class myclass {
const MYCONST = 123;
static $value = 567;
}
echo "myclass::MYCONST = " . myclass::MYCONST . "\n";
echo "myclass::$value = " . myclass::$value . "\n";
?>
Using Static Methods and Properties to Limit Instances of a Class (PHP 5 Only)
<?php
class Shop {
private static $instance;
public $name="shop";
private function ___construct() {
}
public static function getInstance() {
if ( empty( self::$instance ) ) {
self::$instance = new Shop();
}
return self::$instance;
}
}
$first = Shop::getInstance();
$first-> name="A";
$second = Shop::getInstance();
print $second -> name;
?>
Using the -> and :: operators to call hypnotize
<?php
class Cat {
}
class MyCat extends Cat {
function MyCat( ) {
}
public static function hypnotize( ) {
echo ("The cat was hypnotized.");
return;
}
}
MyCat::hypnotize( );
$h_cat = new MyCat( );
$h_cat->hypnotize( );