PHP Objects

Class Objects

Just like the integer, float and character are types of data types, so the class is also a type. The only difference is that the class is a user defined type that the user defines according to its own needs.

Variables of class type are also created. Classes of variables are called objects. With these objects, you store data in different properties defined in the class.

For example, you can create 5 objects of the Employee class created above, and those items can store and access information of 5 employees such as their names.

<?php
class Employee
{
// Property declaration
public $name = "Fred";
// Function declaration
public function emFunction()
{
return $this->name;
}
}
// Creating object
$obj = new Employee();
echo "<h2>Name</h2>".$obj->emFunction()."<h2>is printed using class object.</h2>";
?>

Employee class has been created in the above example. As you can see a property and a function declare within this class. Property is already assigned the value.

Class properties can also pass values ​​while manually creating an object without assigning it. This is done by the constructors which you will learn in the next tutorials. The property is being returned to the inside of the function. $ This keyword has been used in the Function. This keyword is used like the object of the current class. Class members can be accessed only by class objects. So $ this has been used like an object of the Employee class. The $ name property has been accessed from this keyword.

In the end, the object of the Employee class outside the class has been created and emFunction () has been called. This example produces the below given output.