php能php 定义常量数组数组为类的常量吗

Keyboard Shortcuts?
Next menu item
Previous menu item
Previous man page
Next man page
Scroll to bottom
Scroll to top
Goto homepage
Goto search(current page)
Focus search box
Change language:
Brazilian Portuguese
Chinese (Simplified)
可以把在类中始终保持不变的值定义为常量。在定义和使用常量的时候不需要使用 $ 符号。
常量的值必须是一个定值,不能是变量,类属性,数学运算的结果或函数调用。
接口(interface)中也可以定义常量。更多示例见文档中的部分。
自 PHP 5.3.0 起,可以用一个变量来动态调用类。但该变量的值不能为关键字(如
self,parent 或 static)。
Example #1 定义和使用一个类常量
&?phpclass&MyClass{&&&&const&constant&=&'constant&value';&&&&function&showConstant()&{&&&&&&&&echo&&self::constant&.&"\n";&&&&}}echo&MyClass::constant&.&"\n";$classname&=&"MyClass";echo&$classname::constant&.&"\n";&//&自&5.3.0&起$class&=&new&MyClass();$class-&showConstant();echo&$class::constant."\n";&//&自&PHP&5.3.0&起?&
Example #2 静态数据示例
&?phpclass&foo&{&&&&//&自&PHP&5.3.0&起&&&&const&bar&=&&&&'EOT'barEOT;}?&
和 heredoc 不同,nowdoc 可以用在任何静态数据中。
Nowdoc 支持是在 PHP 5.3.0 新增的。
It may seem obvious, but class constants are always publicly visible. They cannot be made private or protected. I do not see it state that in the docs anywhere.
As of PHP 5.6 you can finally define constant using math expressions, like this one:&?phpclass MyTimer {& & const SEC_PER_DAY = 60 * 60 * 24;}?&Me happy :)
const can also be used directly in namespaces, a feature never explicitly stated in the documentation.&?phpnamespace Foo;const BAR = 1;?&&?phprequire 'foo.php';var_dump(Foo\BAR); ?&
it's possible to declare constant in base class, and override it in child, and access to correct value of the const from the static method is possible by 'get_called_class' method:&?phpabstract class dbObject{& & & & const TABLE_NAME='undefined';& & & & public static function GetAll()& & {& & & & $c = get_called_class();& & & & return "SELECT * FROM `".$c::TABLE_NAME."`";& & }& & }class dbPerson extends dbObject{& & const TABLE_NAME='persons';}class dbAdmin extends dbPerson{& & const TABLE_NAME='admins';}echo dbPerson::GetAll()."&br&";echo dbAdmin::GetAll()."&br&";?&
I think it's useful if we draw some attention to late static binding here:&?phpclass A {& & const MY_CONST = false;& & public function my_const_self() {& & & & return self::MY_CONST;& & } & & public function my_const_static() {& & & & return static::MY_CONST;& & } }class B extends A {&& const MY_CONST = true;}$b = new B();echo $b-&my_const_self ? 'yes' : 'no'; echo $b-&my_const_static ? 'yes' : 'no'; ?&
Most people miss the point in declaring constants and confuse then things by trying to declare things like functions or arrays as constants. What happens next is to try things that are more complicated then necessary and sometimes lead to bad coding practices. Let me explain...
A constant is a name for a value (but it's NOT a variable), that usually will be replaced in the code while it gets COMPILED and NOT at runtime.
So returned values from functions can't be used, because they will return a value only at runtime.
Arrays can't be used, because they are data structures that exist at runtime.
One main purpose of declaring a constant is usually using a value in your code, that you can replace easily in one place without looking for all the occurences. Another is, to avoid mistakes.
Think about some examples written by some before me:
1. const MY_ARR = "return array(\"A\", \"B\", \"C\", \"D\");";
It was said, this would declare an array that can be used with eval. WRONG! This is just a string as constant, NOT an array. Does it make sense if it would be possible to declare an array as constant? Probably not. Instead declare the values of the array as constants and make an array variable.
2. const magic_quotes = (bool)get_magic_quotes_gpc();
This can't work, of course. And it doesn't make sense either. The function already returns the value, there is no purpose in declaring a constant for the same thing.
3. Someone spoke about "dynamic" assignments to constants. What? There are no dynamic assignments to constants, runtime assignments work _only_ with variables. Let's take the proposed example:
&?php
class DbConstant extends aClassConstant {
& & protected $host = 'localhost';
& & protected $user = 'user';
& & protected $password = 'pass';
& & protected $database = 'db';
& & protected $time;
& & function __construct() {
& & & & $this-&time = time() + 1; }
}
?&
Those aren't constants, those are properties of the class. Something like "this-&time = time()" would even totally defy the purpose of a constant. Constants are supposed to be just that, constant values, on every execution. They are not supposed to change every time a script runs or a class is instantiated.
Conclusion: Don't try to reinvent constants as variables. If constants don't work, just use variables. Then you don't need to reinvent methods to achieve things for what is already there.
Use CONST to set UPPER and LOWER LIMITSIf you have code that accepts user input or you just need to make sure input is acceptable, you can use constants to set upper and lower limits. Note: a static function that enforces your limits is highly recommended... sniff the clamp() function below for a taste.&?phpclass Dimension{& const MIN = 0, MAX = 800;& public $width, $height;& public function __construct($w = 0, $h = 0){& & $this-&width& = self::clamp($w);& & $this-&height = self::clamp($h);& }& public function __toString(){& & return "Dimension [width=$this-&width, height=$this-&height]";& }& protected static function clamp($value){& & if($value & self::MIN) $value = self::MIN;& & if($value & self::MAX) $value = self::MAX;& & return $value;& }}echo (new Dimension()) . '&br&';echo (new Dimension(1500, 97)) . '&br&';echo (new Dimension(14, -20)) . '&br&';echo (new Dimension(240, 80)) . '&br&';?&- - - - - - - - Dimension [width=0, height=0] - default size Dimension [width=800, height=97] - width has been clamped to MAX Dimension [width=14, height=0] - height has been clamped to MIN Dimension [width=240, height=80] - width and height unchanged- - - - - - - -Setting upper and lower limits on your classes also help your objects make sense. For example, it is not possible for the width or height of a Dimension to be negative. It is up to you to keep phoney input from corrupting your objects, and to avoid potential errors and exceptions in other parts of your code.
Re: "The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call."I dare say that "a mathematical operation" can indeed be a constant expression. I was quite surprise you cannot, for example do something like:const LIMITMB = 20;const LIMITB = LIMITMB * 1024 * 1024;It is very common to be able to express something like that in other languages, like C with #defines, where changing one definition has a cascading effect on others without having to pre-calculate hard-coded numbers all over the place. So beware, you might be better off using a private static or global contstant definition if you need to do anything more sophisticated than a name=primitive value pair.
Class constants are allocated per instance of the class. If you create a class with 100 constants, each with 100 bytes, and 100 instances of that class, you will use 1 million bytes. Obviously that is a fringe case but remember that when you are creating constants that you might not need in every instance.
Noted by another is that class constants take up memory for every instance. I cannot see this functionality being accurate, so testing thusly:class SomeClass { const thing = 0; const thing2 = 1;}$m0 = memory_get_usage();$p0 = new SomeClass();$p1 = new SomeClass();$p2 = new SomeClass();$m1 = memory_get_usage();printf("memory %d&br /&", $m1 - $m0);The output does not change when one alters the count of constants in "SomeClass".
Square or curly bracket syntax can normally be used to access a single byte (character) within a string. For example: $mystring[5]. However, please note that (for some reason) this syntax is not accepted for string class constants (at least, not in PHP 5.5.12).For example, the following code gives "PHP Parse error:& syntax error, unexpected '[' in php shell code on line 6".&?phpclass SomeClass{& const SOME_STRING = '';& public static function ATest()& {& & return self::SOME_STRING[0];& }}?&It looks like you have to use a variable/class member instead.
additional to tmp dot 4 dot longoria at gmail dot com ?s post:quote: it's possible to declare constant in base class, and override it in child,/quoteIts not that we overwrite them.Its more that each got its own:&?php abstract class dbObject{& & const TABLE_NAME='undefined';}class dbPerson extends dbObject{& & const TABLE_NAME='persons';& & public static function getSelf()& & {& & & & return self::TABLE_NAME;& & }& & public static function getParent()& & {& & & & return parent::TABLE_NAME;& & }}class dbAdmin extends dbPerson{& & const TABLE_NAME='admins';& & public static function getSelf()& & {& & & & return self::TABLE_NAME;& & }& & public static function getParent()& & {& & & & return parent::TABLE_NAME;& & }}echo '&pre&im class dbPerson{} and this is my:& & self TABLE_NAME:& & '.dbPerson::getSelf().'&& // persons& & parent TABLE_NAME: '.dbPerson::getParent().'& // undefinedim class dbAdmin{} and this is my:& & self TABLE_NAME:&& '.dbAdmin::getSelf().'& & // admins& & parent TABLE_NAME: '.dbAdmin::getParent().'& // persons'; ?&or more readable:&?phpclass ParentClass{& & const CONSTANT = 'CONST_PARENT';}class A extends ParentClass{& & const CONSTANT = 'CONST_A';& & public static function getSelf()& & {& & & & return self::CONSTANT;& & }& & public static function getParent()& & {& & & & return parent::CONSTANT;& & }}echo '&pre&im class A{} and this is my:& & self CONSTANT:& & '.A::getSelf().'&& // CONST_A& & parent CONSTANT: '.A::getParent().'& // CONST_PARENT';?&
The major problem of constants is for me, you cant use them for binary flags. &?phpclass constant {& & const MODE_FLAG_1 = 1;& & const MODE_FLAG_2 = 2;& & const MODE_FLAG_3 = 4;& & const DEFAULT_MODE = self::FLAG_1 | self::FLAG_2& & private function foo ($mode=self::DEFAULT_MODE) {& & & & }}?&This code will not work because constants can't be an calculation result. You could use&?php& & const DEFAULT_MODE = 3;?&instead, but we use flags to be value indipendent. So you would miss target with it. Only way is to use defines like ever before.
I thought it would be relevant to point out that with php 5.5, you can not use self::class, static::class, or parent::class to produce a FQN. Doing so produces a PHP Parse error:"PHP Parse error:& syntax error, unexpected 'class' (T_CLASS), expecting variable (T_VARIABLE) or '$'"It would be nice if you could do this however.
If you have a class which defines a constant which may be overridden in child definitions, here are two methods how the parent can access that constant:
&?php
class Weather
{
& & const danger = 'parent';
& & static function getDanger($class)
& & {
& & & & }
class Rain extends Weather
{
& & const danger = 'child';
}
?&
The two options to place in the parent accessor are:
& & & & eval('$danger = ' . $class . '::');
& & & &
& & & & $danger = constant($class . '::danger');
I prefer the last option, but they both seem to work.
So, why might this be useful?&& Well, in my case I have a page class which contains various common functions for all pages and specific page classes extend this parent class.&& The parent class has a static method which takes an argument (class name) and returns a new instantiation of the class.&&
Each child class has a constant which defines the access level the user must have in order to view the page.&& The parent must check this variable before creating and returning an instance of the child - the problem is that the class name is a variable and $class::danger will treat $class as an object.
Suprisingly consts are lazy bound even though you use self instead of static:&?phpclass A{& const X=1;& const Y=self::X;}class B extends A{& const X=1.0;}var_dump(B::Y); ?&
&?phpclass MyClass{& & & & & & const CONSTANT& & & =&& 'constant named "CONSTANT" ';& & const small& & & && =&& 'constant named "small" ';& & & & public $small& & & & =&& 'SAME CONTSNAT NAME AS PROPERTIES.';& & & function showConstant() {& & & & echo& self::CONSTANT . "&br&";& & & & }}$class& & & =&& new MyClass();$class-&showConstant();echo $class-&small."&br&";& ?&
class Country{const IND = "India';const PK='Pakistan';contst NK='Nanhe kumar';}$countryCode='IND';constant("Country::$countryCode"); $countryCode='PK';constant("Country::$countryCode");
A useful technique I've found is to use interfaces for package- or application-wide constants, making it easy to incorporate them into any classes that need access to them:&?phpinterface AppConstants{&& const FOOBAR = 'Hello, World.';}class Example implements AppConstants{&& public function test()&& {& & & echo self::FOOBAR;&& }}$obj = new Example();$obj-&test();& ?&I realize the same could be done simply by defining the constant in a class and accessing it via "class_name::const_name", but I find this a little nicer in that the class declaration makes it immediately obvious that you accessing values from the implemented interface.
pre 5.3 can refer a class using variable and get constants with:
&?php
function get_class_const($class, $const){
& return constant(sprintf('%s::%s', $class, $const));
}
class Foo{
& const BAR = 'foobar';
}
$class = 'Foo';
echo get_class_const($class, 'BAR');
?&
Note that since constants are tied to the class definition, they are static by definition and cannot be accessed using the -& operator.A side effect of this is that it's entirely possible for a class constant to have the same name as a property (static or object):&?phpclass Foo{& const foo = 'bar';& public $foo = 'foobar';& const bar = 'foo';& static $bar = 'foobar';}var_dump(foo::$bar); var_dump(foo::bar);& $bar = new Foo();var_dump($bar-&foo); var_dump(bar::foo); ?&
Since constants of a child class are not accessible from the parent class via self::CONST and there is no special keyword to access the constant (like this::CONST), i use private static variables and these two methods to make them read-only accessible from object's parent/child classes as well as statically from outside:&?phpclass b extends a {& & private static $CONST = 'any value';& & public static function getConstFromOutside($const) {& & & & return self::$$const;& & }& & protected function getConst($const) {& & & & return self::$$const;& & }}?&With those methods in the child class, you are now able to read the variables from the parent or child class:&?phpclass a {& & private function readConst() {& & & & return $this-&getConst('CONST');& & }& & abstract public static function getConstFromOutside($const);& & abstract protected function getConst($const);}?&From outside of the object:&?phpecho b::getConstFromOutside('CONST');?&You maybe want to put the methods into an interface.However, class b's attribute $CONST is not a constant, so it is changeable by methods inside of class b, but it works for me and in my opinion, it is better than using real constants and accessing them by calling with eval:&?phpprotected function getConst($const) {& & eval('$value = '.get_class($this).'::'.$const.';');& & return $value;}?&
Lest anyone think this is somehow an omission in PHP, there is simply no point to having a protected or private constant. Access specifiers identify who has the right to *change* members, not who has the right to read them:&?phpclass Test {& & public static $open=2;& & protected static $var=1;& & private static $secret=3;}$classname="Test";$x=new ReflectionClass($classname);$y=array();foreach($x-&GetStaticProperties() as $k=&$v) & & $y[str_replace(chr(0),"@",$k)]=$v;$a=array("open","var","secret","nothing");foreach($a as $b){& & if(isset($y["$b"])) & & & & echo "\"$b\" is public: {$y["$b"]}&br/&";& & elseif(isset($y["@*@$b"])) & & & & echo "\"$b\" is protected: {$y["@*@$b"]}&br/&";& & elseif(isset($y["@$classname@$b"])) & & & & echo "\"$b\" is private: {$y["@$classname@$b"]}&br/&";& & else & & & & echo "\"$b\" is not a static member of $classname&br/&";}?&As you can see from the results of this code, the protected and private static members of Test are still visible if you know where to look. The protection and privacy are applicable only on writing, not reading -- and since nobody can write to a constant at all, assigning an access specifier to it is just redundant.
Using "const" in the global context works:&?phpconst FOO = 'bar';var_dump(FOO);?&php如何定义数组常量
作者:巩文&& 发布时间:日&&热度:5048℃ &&评论:
&php7已经支持定义常量为一个数据了。如下
define('ANIMALS', ['dog', 'cat', 'bird']);
echo ANIMALS['1']; // outputs "cat"
如果你的php版本,是php以下,请看以下解决方案
是这样吗?
& &define('BEST_PHPER',array('name'=&'巩文','address'=&'china'));
My God,明确告诉你不可以;原因是Warning: Constants may only evaluate to scalar values。
也就是说define常量的值;仅允许标量和 null。标量的类型是 integer, float,string 或者 boolean。所以数组是不允许的
通常做法是采用下面的方法去间接地去定义“数组常量”
方法一:采用eval()函数
& & define('BEST_PHPER',"return array('name'=&'巩文','address'=&'china');");
& & $BEST_PHPER=eval(BEST_PHPER);
& & var_dump($BEST_PHPER);
方法二:采用json_encode()函数
& & define('BEST_PHPER',json_encode(array('name'=&'巩文','address'=&'china')));
& & $BEST_PHPER=json_decode(BEST_PHPER,true);
& & var_dump($BEST_PHPER);
方法三:采用serialize()函数
& & define('BEST_PHPER',serialize(array('name'=&'巩文','address'=&'china')));
& & $BEST_PHPER=unserialize(BEST_PHPER);
& & var_dump($BEST_PHPER);
选填,承诺不会泄漏您的邮箱!
超级文本预处理语言Hypertext Preprocessor的缩写。PHP 是一种 HTML 内嵌式的语言,是一种在服务器端执行的嵌入HTML文档的脚本语言,语言风格有类似于C语言,被广泛的运用。新手园地& & & 硬件问题Linux系统管理Linux网络问题Linux环境编程Linux桌面系统国产LinuxBSD& & & BSD文档中心AIX& & & 新手入门& & & AIX文档中心& & & 资源下载& & & Power高级应用& & & IBM存储AS400Solaris& & & Solaris文档中心HP-UX& & & HP文档中心SCO UNIX& & & SCO文档中心互操作专区IRIXTru64 UNIXMac OS X门户网站运维集群和高可用服务器应用监控和防护虚拟化技术架构设计行业应用和管理服务器及硬件技术& & & 服务器资源下载云计算& & & 云计算文档中心& & & 云计算业界& & & 云计算资源下载存储备份& & & 存储文档中心& & & 存储业界& & & 存储资源下载& & & Symantec技术交流区安全技术网络技术& & & 网络技术文档中心C/C++& & & GUI编程& & & Functional编程内核源码& & & 内核问题移动开发& & & 移动开发技术资料ShellPerlJava& & & Java文档中心PHP& & & php文档中心Python& & & Python文档中心RubyCPU与编译器嵌入式开发驱动开发Web开发VoIP开发技术MySQL& & & MySQL文档中心SybaseOraclePostgreSQLDB2Informix数据仓库与数据挖掘NoSQL技术IT业界新闻与评论IT职业生涯& & & 猎头招聘IT图书与评论& & & CU技术图书大系& & & Linux书友会二手交易下载共享Linux文档专区IT培训与认证& & & 培训交流& & & 认证培训清茶斋投资理财运动地带快乐数码摄影& & & 摄影器材& & & 摄影比赛专区IT爱车族旅游天下站务交流版主会议室博客SNS站务交流区CU活动专区& & & Power活动专区& & & 拍卖交流区频道交流区
UID387845空间积分0 积分1207阅读权限30帖子精华可用积分1207 信誉积分456 专家积分0 在线时间1990 小时注册时间最后登录
家境小康, 积分 1207, 距离下一级还需 793 积分
帖子主题精华可用积分1207 信誉积分456 专家积分0 在线时间1990 小时注册时间最后登录
论坛徽章:0
PHP不支持常量作为数组,但是,在一个工程里,常量数组是非常需要的,怎要才能绕过这样的限制
一个叫兲的朝代
胡旋锦堆涛,粥温家难饱
卖文卖名店[url=http://t.cn/SVmsWP]
[url=.cn/?s=6uyXnP][/
&&nbsp|&&nbsp&&nbsp|&&nbsp&&nbsp|&&nbsp&&nbsp|&&nbsp
低调复出~
UID空间积分835 积分1829阅读权限30帖子精华可用积分1829 信誉积分325 专家积分396 在线时间1364 小时注册时间最后登录
家境小康, 积分 1829, 距离下一级还需 171 积分
帖子主题精华可用积分1829 信誉积分325 专家积分396 在线时间1364 小时注册时间最后登录
论坛徽章:0
这样可以哇?
$Status = array{
&&'学生'=&0, '老师'=&1, '校长'=&2
if($myStatus === $Status[&老师&]){
// 做老师的工作
这样可以哇?
2010 平平淡淡才是真

我要回帖

更多关于 常量数组定义 的文章

 

随机推荐