self()是用在類中了這個(gè)new self()用法小編第一次聽說過了,不過看了一些相關(guān)文章 self()與this有那么一像但又不全像,下面我們來看看php中new self()關(guān)鍵字的用法.
php new self()一般在類內(nèi)部使用,作用是對(duì)自身類實(shí)例化,下面給個(gè)實(shí)例講解如何使用:
<?php
class phpernote{
public function __construct(){
echo '武林網(wǎng)!';
}
public static function getInstance(){
new self();
}
}
phpernote::getInstance();
返回結(jié)果:武林網(wǎng)!
例子:
//self是指向類的本身,只跟類有關(guān),跟任何對(duì)象實(shí)例無關(guān)
class test_self{
private static $first_count; //定義靜態(tài)變量
private $last_count;
function __construct(){
$this->last_count=++self::$first_count;//直接用self調(diào)用變量的值賦值給另一個(gè)變量
}
function __destruct(){}
function print_self(){
print($this->last_count);
}
}
$abc=new test_self();//實(shí)例化對(duì)象
$abc->print_self();//1
echo '<br />';
總結(jié):self是指向當(dāng)前類的指針意思就是指類的本身了,所以我們?nèi)绻{(diào)用自己的話就可以這new self來創(chuàng)建了.