本文操作环境: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视频教程》

以上就是php中双冒号的用法是什么的详细内容,更多请关注悠悠之家其它相关文章!

点赞(26)

评论列表共有 0 条评论

立即
投稿
返回
顶部