PHP 5:const与静态 [英] PHP 5: const vs static
本文介绍了PHP 5:const与静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在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不同,可以更改其值. /p>
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.
公共,受保护和私有与const无关(它们始终是公共的);它们仅对类变量(包括静态变量)有用.
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访问.
请务必注意, 查看全文