搜索
首页后端开发PHP问题php const和static变量的区别是什么

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

Mar 31, 2021 pm 06:15 PM
constphpstatic

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

php 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视频教程

以上是php const和static变量的区别是什么的详细内容。更多信息请关注PHP中文网其他相关文章!

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

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。