理解PHP5中static和const关键字的区别
PHP5中加入了很多面向对象的思想,PHP5的面向对象比较接近Java的面向对象思想。我们这里对PHP5中的static和const关键字作用进行一下描述,希望对学习PHP5的朋友有帮助。
(1) static
static关键字在类中是,描述一个成员是静态的,static能够限制外部的访问,因为static后的成员是属于类的,是不属于任何对象实例,其他类是无法访问的,只对类的实例共享,能一定程序对该成员尽心保护。类的静态变量,非常类似全局变量,能够被所有类的实例共享,类的静态方法也是一样的,类似于全局函数。类的静态方法能访问类的静态的属性。另外说明的是,static的成员,必须使用self来访问,使用this会出错。
(关于this和self的异同,请参考: http://blog.csdn.net/heiyeshuwu/archive/2004/11/03/165828.aspx )
(2)const
const是一个定义常量的关键字,类似于C中的#define,能够定义一个常量,如果在程序中改变了它的值,那么会出现错误。
举例说明上面的代码:(注:以下代码来自phpe.net)
复制代码 代码如下:
class Counter
{
private static $count = 0;//定义一个静态属性
const VERSION = 2.0;//定义一个常量
//构造函数
function __construct()
{
self::$count++;
}
//析构函数
function __destruct()
{
self::$count--;
}
//定义一个静态的方法
static function getCount()
{
return self::$count;
}
}
//创建一个实例
$c = new Counter();
//执行打印
print( Counter::getCount(). "
n" ); //使用直接输入类名来访问静态方法Counter::getCount
//打印类的版本
print( "Version useed: " .Counter::VERSION. "
n" );
?>
恩,基本到这里,心里知道的那点东西就讲清楚了,不过我觉得自己对static还有点不理解,请高手指点!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.