Home  >  Article  >  Backend Development  >  What is the usage of double colon in php

What is the usage of double colon in php

WBOY
WBOYOriginal
2022-02-21 15:36:093342browse

In PHP, the double colon refers to the scope-limited operator, which can be used to access static members, that is, using variables to represent the class, and then using the double colon to access the static members outside the class. , the syntax is "test::$static property" or "test::static method".

What is the usage of double colon in php

The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer.

What is the usage of double colon in php

Double colon operator: The Scope Resolution Operator can access static, const and overridden properties and methods in classes.

1. Use variables to access static members

In fact, it is to use variables to represent the class, and then use double colons to access the static members outside the class.

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

When accessing yourself, replace the class name with $SELF, for example:

<?php
class Fruit {
    const CONST_VALUE = &#39;Fruit Color&#39;;
}
 
class Apple extends Fruit
{
    public static $color = &#39;Red&#39;;
 
    public static function doubleColon() {
        echo parent::CONST_VALUE . "\n";
        echo self::$color . "\n";
    }
}
 
Apple::doubleColon();//Fruit Color Red
?>

2. Use parent access

to access the parent class method.

<?php
class Fruit
{
    protected function showColor() {
        echo "Fruit::showColor()\n";
    }
}
 
class Apple extends Fruit
{
    // Override parent&#39;s definition
    public function showColor()
    {
        // But still call the parent function
        parent::showColor();
        echo "Apple::showColor()\n";
    }
}
 
$apple = new Apple();
$apple->showColor();
?>

Running results:

Fruit::showColor()

Apple::showColor()

Recommended learning: "PHP Video Tutorial

The above is the detailed content of What is the usage of double colon in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn