PHP中类属性与类静态变量的访问方法示例

时间:2022-09-07 14:52:32

本文实例讲述了PHP类属性与类静态变量的访问方法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
/* PHP类属性与类静态变量的访问
 * Created on 2016-7-13
 */
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();
?>

运行结果为:hello world

希望本文所述对大家PHP程序设计有所帮助。