A class is a code template that is used to create objects. A class is defined using the class
keyword followed by an arbitrary class name. The class name can contain any combination of letters and numbers, but must not start with a number. The code associated with the class must be enclosed in curly braces, which are specified after the name. A class definition describes what elements will be contained in each new instance of that class. Based on the data received, let’s see the syntax of the class definition using an example:
class Person{ }
Create an instance
Since a class is a template for creating instances, therefore an object is data that is created and structured according to the template defined in the class.
class Person{ } $person = new Person();//create class instance
Properties and methods of the class
class Person//create a new class { public $name, $age;//let's create new properties of a class, it is essentially usual variables with the public access modifier function hello() {// method of our class, in essence it is a usual function but in the middle of a class, often with the access modifier echo "Hello!<br>"; } } $tom = new Person();//create an instance of the class $tom->name = "Tom"; // let us turn to our property $name and set its value "Tom" $tom->age = 36; $personName = $tom->name; //getting the value of the $name property $tom->hello(); //call the class method
You can set certain initial values for properties in the class:
class Person { public $name = "Undefined", $age = 18; function hello() { echo "Hello!<br>"; } }
The keyword this is used to refer to the properties (variables) and methods (functions) of the class:
<?php class Person { public $name = "Undefined", $age = 18; public function displayInfo() { echo "Name: $this->name; Age: $this->age;//refer to the properties within the class } } $tom = new Person(); $tom -> name = "Tom"; $tom -> displayInfo(); // Name: Tom; Age: 18 ?>
“==” two objects are considered equal if they represent the same class and their properties have the same
values.
Example:
class Person { public $name; public function __construct($name) { $this->name = $name; } } $person1 = new Person("John"); $person2 = new Person("John"); $person3 = $person1; var_dump($person1 == $person2); // Return: bool(true) var_dump($person1 === $person2); // Return: bool(false) var_dump($person1 === $person3); // Return: bool(true)
And when using the equivalence operator “===“, both objects are considered equal if both class variables indicate to the same class instance.