search
HomeBackend DevelopmentPHP Tutorialphp类中的$this,static,final,const,self这几个关键字使用方法_PHP

本篇文章主要分项了一下关于php类中的$this,static,final,const,self这几个关键字使用方法。

  $this

  $this表示当前实例,在类的内部方法访问未声明为const及static的属性时,使用$this->value='phpernote';的形式。常见用法如:

  $this->属性

  $this->方法

  举例如下:

<&#63;php
class 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 www.bitsCN.com");
$myclass->printName();//输出:I Like www.bitsCN.com
&#63;>

  在类里面调用当前类的属性和方法有三种方法,分别是self、parent、$this,这三个关键字的区别是:self用来指向当前的类;parent用于指向当前类的父类,可以使用该关键字调用父类的属性和方法;$this用来在类体内调用自身的属性和方法。

  static

  关键字可以是self(在类内部调用静态成员时所使用)静态成员所在的类名(在类外调用类内部的静态成员时所使用)
  声明一个静态变量如下: 

static $val='';

  只存在于函数作用域的变量,函数执行之后变量的值不会丢失,只会初始化一次,初始化静态变量不能使用表达式,不用全局变量代替是因为全局变量会被所有函数访问容易造成维护不宜。
  在类中使用static有两种主要用途、定义静态成员和定义静态方法。静态成员只保留一个变量的值,这个值对所有实例都是有效的,如下:

<&#63;php
class 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

 代码如下

<&#63;php
class 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."位访客";
&#63;>

  结果将是:

  您是滴0位访客
  您是滴1位访客
  您是滴2位访客

  另外需要注意的是如果类的方法是static的,他所访问的属性也必须是static的。

  final

  PHP final关键字可以修饰类同样可以修改类中的方法,但它们的作用是差不多的,即如果你使用了final关键字来修饰了,那么这个被修饰的类或者方法将不能被扩展或者继承。你只能老老实实去引用它。如果你在类前面使用了final,这就是说明这个类不能使用继承;如果你在方法前使用了PHP final关键字,这就是说明这个方法不能被覆盖。道理就是这么简单,让我们也看个简单的示例吧。

  最终的类和方法,不能继承,该关键字修饰的方法不能被重写。一般用法如下:

final class MyClass{//此类将不允许被继承
  final function fun1(){......}//此方法将不允许被重写
  }

  例

 < &#63;PHP  
  final class BaseClass {  
  public function test() {  
  echo "BaseClass::test() calledn";  
  }  
  final public function moreTesting() {  
  echo "BaseClass::moreTesting() calledn";  
  }  
  }  
  class ChildClass extends BaseClass {  
  public function moreTesting() {  
  echo "ChildClass::moreTesting() calledn";  
  }  
  }  
  // Results in Fatal error: Cannot override final method BaseClass::moreTesting()  
  &#63;> 

  const

  在类的内部方法访问已经声明为const及static的属性时,需要使用self::$name的形式调用。举例如下:

<&#63;php
class 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类中的$this,static,final,const,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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor