What is the usage of double colon in php

WBOY
Release: 2023-03-15 12:44:02
Original
3378 people have browsed it

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
?>
Copy after login

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
?>
Copy after login

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();
?>
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!