Home  >  Article  >  php教程  >  深入分析PHP const与define使用区别

深入分析PHP const与define使用区别

WBOY
WBOYOriginal
2016-05-23 13:07:291416browse

const是用于类成员常量的定义了,定义之后不可改,而define我们定义的是全局常量了,这样我们在其它地方访问但不能改变了,具体还有一些细节我们下面给各位列出来吧.

注意:define不能定义在类中,而const必须定义在类中,并且const必须通过类名::变量名来进行访问.

1、const用于类成员变量定义,一旦定义且不能改变其值,define定义全局常量,在任何地方都可以访问.

2、define不能在类中定义而const可以.

3、const不能在条件语句中定义常量

4、const采用一个普通的常量名称,define可以采用表达式作为名称.

5、const只能接受静态的标量,而define可以采用任何表达式.

6、const 总是大小写敏感,然而define()可以通过第三个参数来定义大小写不敏感的常量.

7.使用const简单易读,它本身是一个语言结构,而define是一个方法,用const定义在编译时比define快很多.

define是定义常量的,如果在类中定义常量呢?当然不能用define,而用const,如下例:

<?php 
	//在类外面通常这样定义常量 
	define("PHP","111cn.net"); 
	class MyClass 
	{ 
	    //常量的值将始终保持不变。在定义和使用常量的时候不需要使用$符号 
	    const constant = &#39;constant value&#39;; 
	 
	    function showConstant() { 
	        echo  self::constant . "<br>"; 
	    } 
	} 
	 
	echo MyClass::constant . "<br>"; 
	 
	$classname = "MyClass"; 
	echo $classname::constant . "<br>"; // PHP 5.3.0之后 
	 
	$class = new MyClass(); 
	$class->showConstant(); 
	echo $class::constant."<br>"; // PHP 5.3.0之后 
	//print_r(get_defined_constants());  //可以用get_defined_constants()获取所有定义的常量 
	 

一般是define在类外定义常量,const在类内定义常量,并且const必须通过类名::变量名来进行访问,但是php5.3以上支持类外通过const定义常量,看如下,这样是ok的:

<?php 
	    //@blog<http://www.phprm.com> 
	    const a = "abcdef"; 
	    echo a; 
	 

关于常量的基础知识,这里不说了,除了以上,define和const的其它区别(摘自网络).

1.const不能再条件语句中定义常量,但是define是可以的,如下:

<?php 
	    if(1){ 
	        const a = &#39;java&#39;; 
	    } 
	    echo a;  //必错 
	 

2.const采用一个普通的常量名称,define可以采用表达式作为名称,代码如下:

<?php 
	const  FOO = &#39;PHP&#39;;  
	 
	for ($i = 0; $i < 32; ++$i) {  
	    define(&#39;PHP_&#39; . $i, 1 << $i);  
	}  
	 

3.const只能接受静态的标量,而define可以采用任何表达式,代码如下:

<?php 
	const PHP = 1 << 5;    // 错误 
	define(&#39;PHP&#39;, 1 << 5); // 正确  
	 

4.const本身就是一个语言结构,而define是一个函数,所以使用const速度要快的多.

两个共同步:两者都是不能进行重新赋值.

教程网址:

欢迎收藏∩_∩但请保留本文链接。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn