Table of Contents
php中this,self,parent三个关键字的作用 
$this
static
final
const
self
PHP中 :: 、-> 、self 、$this操作符的区别
PHP双冒号::的用法
Home Backend Development PHP Tutorial php面向对象类中的$this,static,final,const,self这几个关键字使用方法。

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

Jun 23, 2016 pm 01:43 PM

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岁?>
Copy after login

$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>
Copy after login
在类里面调用当前类的属性和方法有三种方法,分别是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
Copy after login
<?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."位访客";?>
Copy after login
结果将是:
您是滴0位访客
您是滴1位访客
您是滴2位访客
另外需要注意的是如果类的方法是static的,他所访问的属性也必须是static的。

final

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

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; 	}}
Copy after login
注意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 = 'Fruit Color';}$classname = 'Fruit';echo $classname::CONST_VALUE; // As of PHP 5.3.0echo Fruit::CONST_VALUE;?>
Copy after login
Program List:在类定义外部使用::

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


Program List:调用parent方法

<?phpclass Fruit{    protected function showColor() {        echo "Fruit::showColor()\n";    }}class Apple extends Fruit{    // Override parent's definition    public function showColor()    {        // But still call the parent function        parent::showColor();        echo "Apple::showColor()\n";    }}$apple = new Apple();$apple->showColor();?>
Copy after login
程序运行结果:
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();?>
Copy after login
程序运行结果: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"!?>
Copy after login
程序运行结果:show color




Statement of this Website
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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between final, finally, and finalize in Java The difference between final, finally, and finalize in Java Feb 19, 2024 pm 12:16 PM

The difference between final, finally, and finalize in Java requires specific code examples. In Java programming, you often encounter the three keywords final, finally, and finalize. Although they are spelled similarly, they have different meanings and usages. This article will explain the differences between these three keywords in detail and give code examples to help readers better understand. 1. Final keyword The final keyword can be used for classes, methods and variables. Its function is to make the modified class

In Java, is it possible to define a constant using only the final keyword? In Java, is it possible to define a constant using only the final keyword? Sep 20, 2023 pm 04:17 PM

A constant variable is a variable whose value is fixed and only one copy exists in the program. Once you declare a constant variable and assign a value to it, you cannot change its value again throughout the program. Unlike other languages, Java does not directly support constants. However, you can still create a constant by declaring a variable static and final. Static - Once you declare a static variable, they will be loaded into memory at compile time, i.e. only one copy will be available. Final - Once you declare a final variable, its value cannot be modified. Therefore, you can create a constant in Java by declaring the instance variable as static and final. Example Demonstration classData{&am

What is the function of java final keyword What is the function of java final keyword Nov 25, 2022 pm 04:26 PM

In Java, final can be used to modify classes, methods and variables. The final modified class means that the class cannot be inherited by any other class, which means that this class is a leaf class in an inheritance tree, and the design of this class has been considered perfect and does not need to be modified or extended. The method in the final modified class means that the class cannot be inherited by any other class and cannot be overridden; that is, the method is locked to prevent the inherited class from changing it. final modifies a variable in a class, indicating that the variable cannot be changed once it is initialized.

Deep understanding of const in C language Deep understanding of const in C language Feb 18, 2024 pm 12:56 PM

Detailed explanation and code examples of const in C In C language, the const keyword is used to define constants, which means that the value of the variable cannot be modified during program execution. The const keyword can be used to modify variables, function parameters, and function return values. This article will provide a detailed analysis of the use of the const keyword in C language and provide specific code examples. const modified variable When const is used to modify a variable, it means that the variable is a read-only variable and cannot be modified once it is assigned a value. For example: constint

How to use const in c language How to use const in c language Sep 20, 2023 pm 01:34 PM

const is a keyword that can be used to declare constants, const modifiers in function parameters, const modified function return values, and const modified pointers. Detailed introduction: 1. Declare constants. The const keyword can be used to declare constants. The value of the constant cannot be modified during the running of the program. The constant can be a basic data type, such as integer, floating point number, character, etc., or a custom data type; 2. The const modifier in the function parameters. The const keyword can be used in the parameters of the function, indicating that the parameter cannot be modified inside the function, etc.

Let's talk about the differences between var, let and const (code example) Let's talk about the differences between var, let and const (code example) Jan 06, 2023 pm 04:25 PM

This article brings you relevant knowledge about JavaScript. It mainly introduces the differences between var, let and const, as well as the relationship between ECMAScript and JavaScript. Interested friends can take a look at it. I hope Helpful to everyone.

18 Ways to Fix Audio Service Not Responding Issue on Windows 11 18 Ways to Fix Audio Service Not Responding Issue on Windows 11 Jun 05, 2023 pm 10:23 PM

Audio output and input require specific drivers and services to work as expected on Windows 11. These sometimes end up running into errors in the background, causing audio issues like no audio output, missing audio devices, distorted audio, etc. How to Fix Audio Service Not Responding on Windows 11 We recommend you to start with the fixes mentioned below and work your way through the list until you manage to resolve your issue. The audio service may become unresponsive for a number of reasons on Windows 11. This list will help you verify and fix most issues that prevent audio services from responding on Windows 11. Please follow the relevant sections below to help you through the process. Method 1: Restart the audio service. You may encounter

What are the correct uses of the const keyword in C++ functions? What are the correct uses of the const keyword in C++ functions? Apr 11, 2024 pm 02:36 PM

Correct usage of the const keyword in C++: Using const to modify a function means that the function will not modify the parameters or class members passed in. Using const to declare a function pointer means that the pointer points to a constant function.

See all articles