Home  >  Article  >  Backend Development  >  Simple example explanation of class constants in php

Simple example explanation of class constants in php

伊谢尔伦
伊谢尔伦Original
2017-06-29 10:13:501100browse

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 = ‘女’;
 
}

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;
       }
 
}

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!

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