Usage of double colon:: in PHP
wx5829dc12698e5 2021-07-28 04:19:04

The double colon operator is the scope limiting operator Scope Resolution Operator Can access static 、const And overridden properties and methods in classes .

If used outside the class definition , Call... With a class name . stay PHP 5.3.0, You can use variables instead of class names .

Program List: Using variables to define external access to a class

1
2
3
4
5
6
7
8
9
10
<?php
class  Fruit {
     const  CONST_VALUE =  'Fruit Color' ;
}
 
$classname  'Fruit' ;
echo  $classname ::CONST_VALUE;  // As of PHP 5.3.0
 
echo  Fruit::CONST_VALUE;
?>

Program List: Used outside the class definition ::

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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();
?>

Program run results :

1
Fruit Color Red

Program List: call parent Method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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();
?>

Program run results :

1
2
Fruit::showColor()
Apple::showColor()

Program List: Use scope qualifiers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
     class  Apple
     {
         public  function  showColor()
         {
             return  $this ->color;
         }
     }
 
     class  Banana
     {
         public  $color ;
 
         public  function  __construct()
         {
             $this ->color =  "Banana is yellow" ;
         }
 
         public  function  GetColor()
         {
             return  Apple::showColor();
         }
     }
 
     $banana  new  Banana;
     echo  $banana ->GetColor();
?>

Program run results :

1
Banana is yellow

Program List: Call the method of the base class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
 
class  Fruit
{
     static  function  color()
     {
         return  "color" ;
     }
 
     static  function  showColor()
     {
         echo  "show "  . self::color();
     }
}
 
class  Apple  extends  Fruit
{
     static  function  color()
     {
         return  "red" ;
     }
}
 
Apple::showColor();
// output is "show color"!
 
?>

Program run results :

1
show color
Please bring the original link to reprint ,thank
Similar articles

2021-06-04

2021-06-05

2021-06-13