php的类属性其实有两种,一种是类常量,一种是类静态变量。两种容易引起混淆。
如同静态类方法和类实例方法一样,静态类属性和实例属性不能重定义(同名),但静态属性可以和类常量同名。
- <?php
- class test
- {
- const constvar='hello world';
- static $staticvar='hello world';
- function getStaticvar(){
- return self::$staticvar;
- }
- }
- $obj=new test();
- echo test::constvar
- echo test::staticvar
- echo test::$staticvar
- $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
- echo test::staticvar
- echo test::$staticvar
- $str='test';
- echo $str::$staticvar
- echo $str::constvar
-
- $obj2=new $str();
- echo $obj2->getStaticvar();
- ?>
|