PHP双冒号::作用域限定操作符详解
日前在百度知道上有人询问PHP中双冒号::的具体用法,因当时使用手机输入较为不便,回答略显简略。今日想起此事,遂在此对PHP中双冒号::的使用场景进行系统总结。
双冒号操作符(Scope Resolution Operator)即作用域限定操作符,其核心功能在于访问静态属性与方法、常量以及子类中重写的父类成员。若在类定义之外使用,需通过类名进行调用;自PHP 5.3.0版本起,支持使用变量动态替代具体的类名。
代码示例:利用变量在类定义外部进行访问
<?php
class Fruit {
const CONST_VALUE = 'Fruit Color';
}
$classname = 'Fruit';
echo $classname::CONST_VALUE; // As of PHP ..
echo Fruit::CONST_VALUE;
?>
Program List:在类定义外部使用::
<?php
class Fruit {
const CONST_VALUE = 'Fruit Color';
}
class Apple extends Fruit
{
public static $color = 'Red';
public static function doubleColon() {
echo parent::CONST_VALUE . "\n";
echo self::$color . "\n";
}
}
Apple::doubleColon();
?>
程序运行结果:
Fruit Color Red
代码示例:调用父类方法
<?php
class Fruit
{
protected function showColor() {
echo "Fruit::showColor()\n";
}
}
class Apple extends Fruit
{
// Override parent's definition
public function showColor()
{
// But still call the parent function
parent::showColor();
echo "Apple::showColor()\n";
}
}
$apple = new Apple();
$apple->showColor();
?>
程序运行结果:
Fruit::showColor() Apple::showColor()
代码示例:使用作用域限定符
<?php
class Apple
{
public function showColor()
{
return $this->color;
}
}
class Banana
{
public $color;
public function __construct()
{
$this->color = "Banana is yellow";
}
public function GetColor()
{
return Apple::showColor();
}
}
$banana = new Banana;
echo $banana->GetColor();
?>
程序运行结果:
Banana is yellow
代码示例:调用基类方法
<?php
class Fruit
{
static function color()
{
return "color";
}
static function showColor()
{
echo "show " . self::color();
}
}
class Apple extends Fruit
{
static function color()
{
return "red";
}
}
Apple::showColor();
// output is "show color"!
?>
程序运行结果:
show color
以上内容详细解析了::在PHP中的多种使用情况,希望能对读者有所帮助。