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();
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)