搜尋
首頁後端開發php教程php面向对象类中的$this,static,final,const,self及双冒号 : 这几个关键字使用方法

php面向对象类中的$this,static,final,const,self及双冒号 :: 这几个关键字使用方法。

php中this,self,parent三个关键字的作用 

this,self,parent三个关键字之间的区别,从字面上比较好理解,分别是指这、自己、父亲。我们先建立几个概念,这三个关键字分别是用在什么 地方呢?我们初步解释一下,this是指向当前对象的指针(姑且用C里面的指针来看吧),self是指向当前类的指针,parent是指向父类的指针。我 们这里频繁使用指针来描述,可能是因为没有更好的语言来表达。

<?php <span style="color:#ff0000;">// this是指向当前对象的指针class test_this{    private $content; //定义变量    function __construct($content){ //定义构造函数          $this->content= $content;    }    function __destruct(){}//定义析构函数    function printContent(){//定义打印函数        echo $this->content.'<br>';    }}$test=new test_this('北京欢迎你!'); //实例化对象$test->printContent();//北京欢迎你!$test=new test_this('新年新气象!');//再一次实例化对象$test->printContent();//新年新气象!echo '<br>';<span style="color:#ff0000;">//self是指向类的本身,只跟类有关,跟任何对象实例无关</span>class test_self{    private static $first_count; //定义静态变量    private $last_count;    function __construct(){        $this->last_count=++self::$first_count;//直接用self调用变量的值赋值给另一个变量    }    function __destruct(){}    function print_self(){        print($this->last_count);    }}$abc=new test_self();//实例化对象$abc->print_self();//1echo '<br>';<span style="color:#ff0000;">//parent是指向父类的指针</span>class test_parent{ //基类    public $name;  //定义姓名  父类成员需要定义为public,才能够在继承类中直接使用 this来调用。    function __construct($name){        $this->name=$name;    }}class test_son extends test_parent{ //派生类  继承test_parent    public $gender;//定义性别    public $age;    //定义年龄    function __construct($gender,$age){ //继承类的构造函数        parent::__construct('nostop');//使用parent调用父类的构造函数,来进行对父类的实例化        $this->gender=$gender;        $this->age=$age;    }    function __destruct(){}    function print_info(){        echo $this->name.'是个'.$this->gender.',今年'.$this->age.'岁'.'<br>';    }}$nostop=new test_son('女性','22');//实例化test_son对象$nostop->print_info();//执行输出函数  nostop是个女性,今年23岁?>

$this

$this表示当前实例,在类的内部方法访问未声明为const及static的属性时,使用$this->value='phpernote';的形式。常见用法如:
$this->属性
$this->方法
举例如下:
查看代码打印
<span style="font-size:14px;"><?phpclass MyClass{	private $name;	public  function __construct($name){		$this->name=$name;	}	public function getname(){		return $this->name;	}	public  function printName(){		echo $this->getname();	}}$myclass= new MyClass("I Like PHP");$myclass->printName();//输出:I Like PHP?></span>
在类里面调用当前类的属性和方法有三种方法,分别是self、parent、$this,这三个关键字的区别是:self用来指向当前的类;parent用于指向当前类的父类,可以使用该关键字调用父类的属性和方法;$this用来在类体内调用自身的属性和方法。

static

关键字可以是self(在类内部调用静态成员时所使用)静态成员所在的类名(在类外调用类内部的静态成员时所使用)
声明一个静态变量如下:
static $val='';
只存在于函数作用域的变量,函数执行之后变量的值不会丢失,只会初始化一次,初始化静态变量不能使用表达式,不用全局变量代替是因为全局变量会被所有函数访问容易造成维护不宜
类中使用static有两种主要用途、定义静态成员和定义静态方法。静态成员只保留一个变量的值,这个值对所有实例都是有效的,如下:
<?phpclass MyObject{	public static $myStaticVar=0;	function myMethod(){		self::$myStaticVar+=2;		echo self::$myStaticVar;	}}$instance1=new MyObject();$instance1->myMethod();$instance2=new MyObject();$instance2->myMethod();//结果将分别打印2、4
<?phpclass Book{	static $num=0;	public function showMe(){		echo"您是滴".self::$num."位访客";		self::$num++;	}}$book1=new Book();$book1->showMe();echo"<br>";$book2=new Book();$book2->showMe();echo"<br>";echo"您是滴".Book::$num."位访客";?>
结果将是:
您是滴0位访客
您是滴1位访客
您是滴2位访客
另外需要注意的是如果类的方法是static的,他所访问的属性也必须是static的。

final

最终的类和方法,不能继承,该关键字修饰的方法不能被重写。一般用法如下:
<?phpfinal class MyClass{//此类将不允许被继承	final function fun1(){......}//此方法将不允许被重写}

const

在类的内部方法访问已经声明为const及static的属性时,需要使用self::$name的形式调用。举例如下:
<?phpclass clss_a{	private static $name="static class_a"; 	const PI=3.14; 	public $value; 	public static function getName(){ 		return self::$name; 	} 	//这种写法有误,静态方法不能访问非静态属性 	public static function getName2(){ 		return self::$value; 	} 	public function getPI(){ 		return self::PI; 	}}
注意const属性的申明格式是const PI=3.14,而不是const $PI=3.14。

self

self表示类本身,指向当前的类。通常用来访问类的静态成员、方法和常量。

PHP中 :: 、-> 、self 、$this操作符的区别

在访问PHP类中的成员变量或方法时,如果被引用的变量或者方法被声明成const(定义常量)或者static(声明静态),那么就必须使用操作符::,反之如果被引用的变量或者方法没有被声明成const或者static,那么就必须使用操作符->。
另外,如果从类的内部访问const或者static变量或者方法,那么就必须使用自引用的self,反之如果从类的内部访问不为const或者static变量或者方法,那么就必须使用自引用的$this。

PHP双冒号::的用法

双冒号操作符即作用域限定操作符Scope Resolution Operator可以访问静态、const和类中重写的属性与方法
在类定义外使用的话,使用类名调用。在PHP 5.3.0,可以使用变量代替类名。Program List:用变量在类定义外部访问。

<?phpclass Fruit {    const CONST_VALUE = &#39;Fruit Color&#39;;}$classname = &#39;Fruit&#39;;echo $classname::CONST_VALUE; // As of PHP 5.3.0echo Fruit::CONST_VALUE;?>
Program List:在类定义外部使用::

<?phpclass Fruit {    const CONST_VALUE = &#39;Fruit Color&#39;;}class Apple extends Fruit{    public static $color = &#39;Red&#39;;    public static function doubleColon() {        echo parent::CONST_VALUE . "\n";        echo self::$color . "\n";    }}
程序运行结果:Fruit Color Red


Program List:调用parent方法

<?phpclass Fruit{    protected function showColor() {        echo "Fruit::showColor()\n";    }}class Apple extends Fruit{    // Override parent&#39;s definition    public function showColor()    {        // But still call the parent function        parent::showColor();        echo "Apple::showColor()\n";    }}$apple = new Apple();$apple->showColor();?>
程序运行结果:
Fruit::showColor()
Apple::showColor()

Program List:使用作用域限定符

  <?php class Apple    {        public function showColor()        {            return $this->color;        }    }    class Banana    {        public $color;        public function __construct()        {            $this->color = "Banana is yellow";        }        public function GetColor()        {            return Apple::showColor();        }    }    $banana = new Banana;    echo $banana->GetColor();?>
程序运行结果:Banana is yellow

Program List:调用基类的方法

    <?phpclass Fruit{    static function color()    {        return "color";    }    static function showColor()    {        echo "show " . self::color();    }}class Apple extends Fruit{    static function color()    {        return "red";    }}Apple::showColor();// output is "show color"!?>
程序运行结果:show color




陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
高流量網站的PHP性能調整高流量網站的PHP性能調整May 14, 2025 am 12:13 AM

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

PHP中的依賴注入:初學者的代碼示例PHP中的依賴注入:初學者的代碼示例May 14, 2025 am 12:08 AM

你應該關心DependencyInjection(DI),因為它能讓你的代碼更清晰、更易維護。 1)DI通過解耦類,使其更模塊化,2)提高了測試的便捷性和代碼的靈活性,3)使用DI容器可以管理複雜的依賴關係,但要注意性能影響和循環依賴問題,4)最佳實踐是依賴於抽象接口,實現鬆散耦合。

PHP性能:是否可以優化應用程序?PHP性能:是否可以優化應用程序?May 14, 2025 am 12:04 AM

是的,優化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)優化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,並避免使用

PHP性能優化:最終指南PHP性能優化:最終指南May 14, 2025 am 12:02 AM

theKeyStrategiestosigantificallyBoostPhpaPplicationPerformenCeare:1)UseOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)優化AtabaseInteractionswithPreparedStateTementStatementStatementAndProperIndexing,3)配置

PHP依賴注入容器:快速啟動PHP依賴注入容器:快速啟動May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增強codemodocultion,可驗證性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依賴注入與服務定位器PHP中的依賴注入與服務定位器May 13, 2025 am 12:10 AM

選擇DependencyInjection(DI)用於大型應用,ServiceLocator適合小型項目或原型。 1)DI通過構造函數注入依賴,提高代碼的測試性和模塊化。 2)ServiceLocator通過中心註冊獲取服務,方便但可能導致代碼耦合度增加。

PHP性能優化策略。PHP性能優化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)啟用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替換loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP電子郵件驗證:確保正確發送電子郵件PHP電子郵件驗證:確保正確發送電子郵件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化進行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具