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

本文操作环境:Windows10系统、PHP7.1版、Dell G3电脑。
双冒号操作符:即作用域限定操作符Scope Resolution Operator可以访问静态、const和类中重写的属性与方法。
1.用变量访问静态成员
其实就是用变量把类表示出来,再用双冒号再类外部访问其中的静态成员。
立即学习“PHP免费学习笔记(深入)”;
<?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中双冒号的用法是什么的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号