国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

php class中self,parent,this的區別以及實例介紹

2024-05-04 23:08:15
字體:
來源:轉載
供稿:網友

一,this

1,要用this,你必有是一個對像的形勢,不然它會報錯的,Fatal error: Using $this when not in object context。
2,this可以調用本類中的方法和屬性,也可以調用父類中的可以調的方法和屬性

二,self

1,self可以訪問本類中的靜態屬性和靜態方法,可以訪問父類中的靜態屬性和靜態方法。
2,用self時,可以不用實例化的


三,parent

1,parent可以訪問父類中的靜態屬性和靜態方法。
2,用parent時,可以不用實例化的

復制代碼 代碼如下:


<?php

class test{
public $public;
private $private;
protected $protected;
static $instance;
static $good = 'tankzhang <br>';
public $tank = 'zhangying <br>';

public function __construct(){
$this->public = 'public<br>';
$this->private = 'private <br>';
$this->protected = 'protected <br>';

}
public function tank(){//私有方法不能繼承,換成public,protected
if (!isset(self::$instance[get_class()]))
{
$c = get_class();
self::$instance = new $c;
}
return self::$instance;
}

public function pub_function() {
echo "you request public function<br>";
echo $this->public;
}
protected function pro_function(){
echo "you request protected function<br>";
echo $this->protected;
}
private function pri_function(){
echo "you request private function<br>";
echo $this->private;
}
static function sta_function(){
echo "you request static function<br>";
}
}

class test1 extends test{

static $love = "tank <br>";
private $aaaaaaa = "ying <br>";

public function __construct(){
parent::tank();
parent::__construct();
}
public function tank(){
echo $this->public;
echo $this->protected;
echo $this->aaaaaaa;
$this->pro_function();
}

public function test1_function(){
echo self::$love;
echo self::$good;
echo parent::$good;
echo parent::$tank; //Fatal error: Access to undeclared static property: test::$tank
echo self::$tank;//Fatal error: Access to undeclared static property: test::$tank
}
static function extends_function(){
parent::sta_function();
self::pro_function();
echo "you request extends_private function<br>";
}
}

error_reporting(E_ALL);
$test = new test1();
$test->tank();//子類和父類有相同名字的屬性和方法,實例化子類時,會調用子類中的方法。
test1::test1_function();
test1::extends_function(); //執行一部分后,報Fatal error: Using $this when not in object context in D:/xampp/htdocs/mytest/www4.php on line 32
?>

1,當我們調用$test->tank(); 這個方法時,tank里面的$this是一個對像 ,這個對像可以調用本類,父類中的方法和屬性,

2,test1::test1_function(); 當我們用靜態的方法去調用非靜態方法時,會顯示警告的,Non-static method test::test1_function() should not be called statically可以看出不,self可以調用本類,父類中的靜態屬性 ,parent可以調用父類中的靜態屬性 ,二者調用非靜態屬性會報錯。代碼中有注釋

3,test1::extends_function(); 這一步會報錯,報在非對像中使用$this 。為什么會這樣呢,test1::extends_function();只是調用了class中的一個方法,并沒有實例化,所以根本不存在什么對像,當父類中用到$this時,就會報錯

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 张北县| 武功县| 永济市| 嘉荫县| 贺州市| 濮阳市| 横山县| 黑山县| 常宁市| 东兴市| 潮州市| 天门市| 大足县| 阳江市| 澄迈县| 盐亭县| 津南区| 中宁县| 额尔古纳市| 北京市| 闽清县| 达孜县| 芮城县| 内丘县| 外汇| 新巴尔虎左旗| 瑞丽市| 乌鲁木齐县| 宁陵县| 台前县| 徐汇区| 兴义市| 万载县| 涿鹿县| 遂溪县| 南丰县| 太仓市| 扎鲁特旗| 漠河县| 故城县| 广河县|