Home  >  Article  >  Backend Development  >  PHP self关键字指向类静态变量

PHP self关键字指向类静态变量

WBOY
WBOYOriginal
2016-06-20 13:00:371331browse

PHP self关键字指向类静态变量

首先我们要明确一点,self是指向类本身,也就是PHP self关键字是不指向任何已经实例化的对象,一般self使用来指向类中的静态变量。

< ?php 
class Counter 
{ 
//定义属性,包括一个静态变量 
private static $firstCount = 0; 
private $lastCount; 
//构造函数 
function __construct() 
{ 
$this->lastCount = ++selft
::$firstCount;
//使用PHP self关键字来调用静态变量,使用self
调用必须使用::(域运算符号) 
} 
//打印最次数值 
function printLastCount() 
{ 
print( $this->lastCount ); 
}  
} 
//实例化对象 
$countObject = new Counter(); 
$countObject->printLastCount();
//输出 1 
?>


我们这里只要注意两个地方,第6行和第12行。我们在第二行定义了一个静态变量$firstCount,并且初始值为0,那么在12行的时候调用了这个值 得,使用的是PHP self关键字来调用,并且中间使用"::"来连接,就是我们所谓的域运算符。
那么这时候我们调用的就是类自己定义的静态变量$ frestCount,我们的静态变量与下面对象的实例无关,它只是跟类有关,那么我调用类本身的的,那么我们就无法使用this来引用,可以使用PHP self关键字来引用,因为self是指向类本身,与任何对象实例无关。换句话说,假如我们的类里面静态的成员,我们也必须使用self来调用。


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