PHP 5:常量与静态 [英] PHP 5: const vs static
本文介绍了PHP 5:常量与静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 PHP 5 中,使用 const
和 static
有什么区别?
In PHP 5, what is the difference between using const
and static
?
什么时候合适?public
、protected
和 private
扮演什么角色 - 如果有的话?
When is each appropriate? And what role does public
, protected
and private
play - if any?
推荐答案
在类的上下文中,静态变量位于类范围(而不是对象)范围内,但与 const 不同的是,它们的值可以更改.
In the context of a class, static variables are on the class scope (not the object) scope, but unlike a const, their values can be changed.
class ClassName {
static $my_var = 10; /* defaults to public unless otherwise specified */
const MY_CONST = 5;
}
echo ClassName::$my_var; // returns 10
echo ClassName::MY_CONST; // returns 5
ClassName::$my_var = 20; // now equals 20
ClassName::MY_CONST = 20; // error! won't work.
Public、protected 和 private 与常量(始终是公共的)无关;它们只对类变量有用,包括静态变量.
Public, protected, and private are irrelevant in terms of consts (which are always public); they are only useful for class variables, including static variable.
- 可以通过 ClassName::$variable 在任何地方访问公共静态变量.
- 定义类或扩展类可以通过 ClassName::$variable 访问受保护的静态变量.
- 私有静态变量只能由定义类通过 ClassName::$variable 访问.
请务必注意PHP 7.1.0 引入了对指定类常量可见性的支持.
这篇关于PHP 5:常量与静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文