在PHP中,双冒号指的是作用域限定操作符,可以用于访问静态成员,也就是用变量将类表示出来,再用双冒号在类的外部访问其中的静态成员,语法为“test::$静态属性”或“test::静态方法”。

本文操作环境:Windows10系统、PHP7.1版、Dell G3电脑。

php中双冒号的用法是什么

双冒号操作符:即作用域限定操作符Scope Resolution Operator可以访问静态、const和类中重写的属性与方法。

1.用变量访问静态成员

其实就是用变量把类表示出来,再用双冒号再类外部访问其中的静态成员。

<?php
class Fruit{
const CONST_VALUE='fruit color';
}
$classname='Fruit';
echo $classname::CONST_VALUE;//fruit color
?>

访问自己的时候就把类名换成$SELF,例如:

<?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
?>

2.用parent访问

访问父类的方法。

<?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中双冒号的用法是什么