Examples of Constant Usage for PHP Object Oriented Programming

  • 2021-07-13 04:47:31
  • OfStack

Class constant is a very important concept in PHP object-oriented programming. A firm grasp of class constant is helpful to improve the level of PHP object-oriented programming. This paper describes the usage of class constants in PHP programming in the form of examples. The details are as follows:

Class constant: In a class, the constant data during the running cycle is stored.

Definition:


const  Keyword 
const  Constant name  =  Constant value 

Examples are as follows:


class Student
{
public $stu_id;
public $stu_name;
public $stu_gender;
const GENDER_MALE= ' Male ';
const GENDER_FEMALE = ' 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= ' Male ';
const GENDER_FEMALE = ' 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 in which $this is located?
The answer is no! Because the value of $this does not depend on the class in which $this is located, but on the execution object (execution environment) when the method in which $this is located is called

Method, the object in which the current method is executed, and the $this in the method represents the object in which the current method is executed.


Related articles: