PHP 类属性 类静态变量的访问
php的类属性其实有两种,一种是类常量,一种是类静态变量。两种容易引起混淆。
如同静态类方法和类实例方法一样,静态类属性和实例属性不能重定义(同名),但静态属性可以和类常量同名。
<?php class test { const constvar= 'hello world' ; static $staticvar = 'hello world' ; function getStaticvar(){ return self:: $staticvar ; } } $obj = new test(); echo test::constvar //输出'hello world' echo test::staticvar //出错,staticvar 前必须加$才能访问,这是容易和类常量(per-class常量)容易混淆的地方之一 echo test:: $staticvar //输出'hello world' $str = 'test' ; echo $str :: $staticvar //出错,类名在这不能用变量动态化 echo $str ::constvar //出错原因同上 //在类名称存在一个变量中处于不确定(动态)状态时,只能以以下方式访问类变量 $obj2 = new $str (); echo $obj2 ->getStaticvar(); ?> <?php class test { const constvar= 'hello world' ; static $staticvar = 'hello world' ; function getStaticvar(){ return self:: $staticvar ; } } $obj = new test(); echo test::constvar //输出'hello world' echo test::staticvar //出错,staticvar 前必须加$才能访问,这是容易和类常量(per-class常量)容易混淆的地方之一 echo test:: $staticvar //输出'hello world' $str = 'test' ; echo $str :: $staticvar //出错,类名在这不能用变量动态化 echo $str ::constvar //出错原因同上 //在类名称存在一个变量中处于不确定(动态)状态时,只能以以下方式访问类变量 $obj2 = new $str (); echo $obj2 ->getStaticvar(); ?>查看更多关于PHP 类属性 类静态变量的访问 - php面向对象的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did29709