Simple example explanation of class constants in php

伊谢尔伦
Release: 2023-03-11 22:18:02
Original
1098 people have browsed it

ClassConstant: In the class, data that remains unchanged during the running cycle is saved.

Definition:

const keyword

const constant name = constant value

Example:

class Student
{
       public  $stu_id;
       public  $stu_name;
       public  $stu_gender;
      
       const  GENDER_MALE = ‘男’;
       const  GENDER_FEMALE = ‘女’;
 
}
Copy after login

Class constants are not restricted by the access qualification modifier

Access:

Class::Constant name

Example:

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;
       }
 
}
Copy after login

Summary: The members that can be defined in a class are: constants, staticproperties, non-static properties, static methods, and non-static methods.

Note: $this represents the current object, does it always represent the object of the class where $this belongs?

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 indicates which object.

The above is the detailed content of Simple example explanation of class constants in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!