Home >Backend Development >PHP Tutorial >PHP object-oriented programming and other constant usage examples, sed usage examples_PHP tutorial
Class constants are a very important concept in PHP object-oriented programming. A firm grasp of class constants will help further improve the level of PHP object-oriented programming. This article describes the usage of class constants in PHP programming in the form of examples. The details are as follows:
Class constant: In the class, data that remains unchanged during the running cycle is saved.
Definition:
const 关键字 const 常量名 = 常量值
Examples are as follows:
class Student { public $stu_id; public $stu_name; public $stu_gender; const GENDER_MALE= '男'; const GENDER_FEMALE = '女'; }
Class constants are not restricted by access qualification modifiers
Access method:
Class::Constant name
Examples are as follows:
class Student { public $stu_id; public $stu_name; public $stu_gender; const GENDER_MALE= '男'; const GENDER_FEMALE = '女'; public function __construct($id,$name,$gender='') { $this->stu_id= $id; $this->stu_name= $name; $this->gender= ($gender == ' ')?self::GENDER_MALE : $gender; } }
Summary: The members that can be defined in a class are: constants, static properties, non-static properties, static methods, and non-static methods .
Note here:
$this represents the current object, so does it always represent the object of the class where $this belongs?
The answer is no! Because the value of $this does not depend on the class where $this is located, but depends on the execution object (execution environment) when the method where $this is located is called
The execution environment of the method, in which object the current method is executed, $this in the method represents which object.
Object-Oriented Programming (OOP) is based on creating software reusable code and has the ability to better simulate real-world environments, which makes it recognized as top-down programming. winner. It "encapsulates" functions into "objects" necessary for programming by adding extension statements to the program. The object-oriented programming language makes complex work clear and easy to write
Final constant means that it is not allowed to be modified, which means it has the same meaning as the constant in C language.
Final function means it is not allowed to be overridden after inheritance.
If the final flag is not used, it will not report an error even if it is modified, and the stability of the program will be affected.