PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

php const和static变量的区别是什么

青灯夜游
青灯夜游 原创
2021-03-31 18:15:56 2346浏览

区别:const一旦被定义不可更改,static修饰的变量是可以被更改的。const只可以修饰类的属性,不能修饰类的方法;static可以修饰属性,也可以修饰方法。

本教程操作环境:windows7系统、PHP7.1版,DELL G3电脑

PHP中 static 与 const 变量的区别

static变量

1.static静态变量 我们可以对于其 进行修改,但是const变量我们不能对其进行修改
2.static 静态变量可以对其修改权限
3.和java类似,在类的内部,satic 修饰的方法的体内无法访问类的非staic成员变量,只能访问类的staic变量和类的const常量

class staticTest1 {
    var $var1 = "hello";
    public static $var2 = "hellostatic"; //public, protected, private
    const var3 = "helloconst";
    public static function displayDifferent(){
###        echo $this->$var1."<br>";//不能访问普通变量
        echo staticTest1::$var2."<br>";//可以访问类的静态变量
        echo self::var3."<br>";//不能用$this::var3, self::var3代表当前类,$this::var3代表当前对象
    }
}

//可以用两种方法调用方法

//第一种,通过对象调用
$test1 = new staticTest1();
echo $test1->displayDifferent();
echo "<br>";
//第二种,通过类调用
echo staticTest1::displayDifferent();
echo "<br>";

顺便一提,”::” 对于对象而言只能访问静态变量和方法,还有self只能用”::”来调用当前类的成员

const变量

1.const变量只能修饰成员变量,不能修饰方法
2.不需要加修饰权限
3.因为const变量属于整个类的,不属于某个对象,所以不能通过对象来访问,像$this->constvariable就不允许

class constTest1 {
    var $var1 = "welcome";
//    public const pi = 3.14;//不能加修饰权限
    const pi = 3.14;
//    const function displayDifferent() {//function前不能加const
//        
//    }
   function displayDifferent() {
        echo self::pi."<br>";
//        echo $this::pi."<br>"; 
    }
    static function displayDifferent2() {
        echo self::pi."<br>";
//        echo $this::pi."<br>"; //这句话不行。
    }
}

两种方法调用

//第一种,通过对象调用
$test2 = new constTest1();
echo $test2->displayDifferent();
//第二种,通过类调用
//echo constTest1::displayDifferent();//对象名用"::"只能访问静态变量和方法,所以这个不行

echo constTest1::displayDifferent2();

推荐学习:《PHP视频教程

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。