search
Homephp教程php手册理解PHP5中static和const关键字的区别

理解PHP5中static和const关键字的区别

Jun 13, 2016 pm 12:32 PM
constphp5staticKeywordsjoin inthe differenceandobjectThoughtunderstandofFor

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还有点不理解,请高手指点!
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.