雙冒號::被認為是作用域限定操作符,用來指定類中不同的作用域級別。::左邊表示的是作用域,右邊表示的是訪問的成員。
系統定義了兩個作用域,self和parent。self表示當前類的作用域,在類之外的代碼是不能使用這個操作符的。
<?php
class NowaClass
{
function nowaMethod()
{
print '我在類 NowaClass 中聲明了。';
}
}
class ExtendNowaClass extends NowaClass
{
function extendNowaMethod()
{
print 'extendNowaMethod 這個方法在 ExtendNowaClass 這個類中聲明了。';
self::nowaMethod();
}
}
ExtendNowaClass::extendNowaMethod();
?>
程序運行結果:
extendNowaMethod 這個方法在 ExtendNowaClass 這個類中聲明了。 我在類 NowaClass 中聲明了。
parent這個作用域很簡單,就是派生類用來調用基類的成員時候使用。
<?php
class NowaClass
{
function nowaMethod()
{
print '我是基類的函數。';
}
}
class ExtendNowaClass extends NowaClass
{
function extendNowaMethod()
{
print '我是派生類的函數。';
parent::nowaMethod();
}
}
$obj = new ExtendNowaClass();
$obj -> extendNowaMethod();
?>
程序運行結果:
我是派生類的函數。 我是基類的函數。
如何繼承一個存儲位置上的靜態屬性。
<?php
class Fruit
{
public function get()
{
echo $this->connect();
}
}
class Banana extends Fruit
{
private static $bananaColor;
public function connect()
{
return self::$bananaColor = 'yellow';
}
}
class Orange extends Fruit {
private static $orange_color;
public function connect()
{
return self::$orange_color = 'orange';
}
}
$banana = new Banana();
$orange = new Orange();
$banana->get();
$orange->get();
?>
程序運行結果:
yellow orange。
在一個類中初始化靜態變量比較復雜,你可以通過創建一個靜態函數創建一個靜態的構造器,然後在類聲明後馬上調用它來實現初始化。
<?php
class Fruit
{
private static $color = "White";
private static $weigth;
public static function init()
{
echo self::$weigth = self::$color . " Kilogram!";
}
}
Fruit::init();
?>
程序運行結果:
White Kilogram!
這個應該可以幫到某些人吧。
<?php
class Fruit
{
private static $instance = null;
private function __construct()
{
$this-> color = 'Green';
}
public static function getInstance()
{
if(self::$instance == null)
{
print "Fruit object created!<br />";
self::$instance = new self;
}
return self::$instance;
}
public function showColor()
{
print "My color is {$this-> color}!<br>";
}
public function setColor($color)
{
$this-> color = $color;
}
}
$apple = Fruit::getInstance(); // Fruit object created!
$apple-> showColor(); // My color is Green!
$apple-> setColor("Red");
$apple-> showColor(); // My color is Red!
$banana = Fruit::getInstance();
$banana-> showColor(); // My color is Red!
$banana-> setColor("Yellow");
$apple-> showColor(); // My color is Yellow!
?>
程序運行結果:
Fruit object created! My color is Green! My color is Red! My color is Red! My color is Yellow!