静态属性是属于类的属性,而不是属于对象的属性。它们可以在类的内部和外部被访问和修改,不需要创建对象。在类的定义中,使用static
关键字来定义静态属性。例如,下面的代码定义了一个Person
类,其中包含一个静态属性$count
:
class Person {
public static $count = 0;
public function __construct() {
self::$count++;
}
public static function getCount() {
return self::$count;
}
}
$p1 = new Person();
$p2 = new Person();
$p3 = new Person();
echo Person::$count; // 输出:3
echo Person::getCount(); // 输出:3
在上面的代码中,我们定义了一个Person
类,其中包含一个静态属性$count
,以及一个构造函数__construct()
和一个静态方法getCount()
。在构造函数__construct()
中,我们使用self::$count++
来增加静态属性$count
的值。在静态方法getCount()
中,我们返回静态属性$count
的值。然后,我们创建了三个Person
对象,每次创建一个对象时,都会调用构造函数__construct()
,从而增加静态属性$count
的值。在外部,我们可以通过类名和::
运算符来访问静态属性和静态方法。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有