Home > Article > Backend Development > Class operations in PHP
The content of this article is about the operation of classes in PHP. It has certain reference value. Now I share it with everyone. Friends in need can refer to it
<?php 权限修饰符 class 类名{ 类的内容; } ?>
Permission modifier can be omitted. At this time, the default modifier is public, which means that each property and method Items are accessible from both inside and outside the class;
Properties and methods declared with the keyword private are only accessible from Access inside the class;
The properties and methods declared with the keyword protected can only be accessed from inside the class, but"Subclasses" generated through "inheritance" can also access these properties and methods.
class Student { public $name;/*类的成员属性,修饰关键词publlic、protected、private,如果没有特定的意义,仍然需要用var关键词修饰*/ function GetIp(){ //方法的内容; } $lili=new 类名称();//类的实例化
On the contrary, if the referenced variable or method is not declared as const or static, then You must use the operator ->.
In addition, if you access a const or static variable or method from within the class, you must use the self-referenced self.
On the contrary, if you access a non-const or static variable or method from within the class, you must use Self-referential $this.
Conclusion: The functions of self and $this are very similar, but they are not the same. $this cannot refer to static members and constants. self is more like the class itself, and $this is more like the instance itself.
4. Construction method and destructor method
The construction method __construct() is automatically called when instantiating the object
Purpose: Can be used in initialization programs (can assign values to member attributes or call member methods)
Syntax: [Modifier] function __construct(parameter list...){ }
Constructor method format:
[Modifier] function __construct([parameter]){
Program body
}
用途:可以进行资源释放操作或文件的关闭操作
注意:如果类中没有构造方法\析构方法,PHP引擎会自动添加一个构造方法\析构方法,其参数列表为空,方法内容为空
class 子类名称 extends 父类名称{ //子类成员变量列表 function 成员方法(){//子类成员方法 //方法内容 } }# when the program ends
##The parent class has the public properties and methods of its subclass. In addition to the public properties and methods of the parent class, the subclass also has its own unique properties and methods.
If a method in the parent class is declared final, the subclass cannot override the method, and the final keyword can terminate the inheritance of the class.
Final classes cannot have subclasses, and final methods cannot be overridden.
Related recommendations:
The difference between abstract classes and interfaces in phpThe above is the detailed content of Class operations in PHP. For more information, please follow other related articles on the PHP Chinese website!