PHP - Classes and Objects
PHP is an object-oriented programming language and it allows us to create objects. To create an object, first of all, the object should be defined in the program which is done by creating a class. A class is a code template that is used to define a new object type. Within a class, the object's properties and methods are defined and when an object is created, its properties and methods are determined by the class in which it is created.
Create Class
To create a class in PHP, class keyword is used. It starts with the keyword followed by class name and a pair of curly braces { }. All its properties and methods goes inside the braces:
Syntax
//defining a class class className { access_specifier property; access_specifier method; };
access_specifier: It defines the access type of the class members (properties and methods). There are three types of access specifier in PHP.
- public: members of the class are accessible from everywhere. It is also default access specifier.
- protected: members of the class are accessible within the class and by derived classes.
- private: members of the class are ONLY accessible within the class.
Note: If no access specifier is mentioned for a member of a class, PHP automatically assigns public access specifier.
Create Object
To create an object, new keyword followed by class name must be assigned to a variable (object name). To access the member of the class, arrow operator -> is used. See the syntax below:
Syntax
//creating an object objectName = new className(); //access class properties and methods objectName->property objectName->method(parameters)
Example:
In the example below, a class (new object type) called person is created. An object called p1 of the class person is created. The object has only one public property name which is accessed in the program using the arrow operator ->.
<?php class person { public $name = "John"; }; $p1 = new person(); echo $p1->name; ?>
The output of the above code will be:
John
Class Methods
Class method also known as class function must be defined inside the class definition. It is defined in the same way as a normal function is defined in PHP.
Example:
In the example below, a class method called info is defined inside the class person. A class method is accessed in the same way as a class property, i.e, using arrow operator ->. Here, the info() class method is used to print the object's property in a given format.
<?php class person { private $name = "John"; private $city = "London"; public function info() { echo $this->name." lives in ".$this->city.".\n"; } }; $p1 = new person(); $p1->info(); ?>
The output of the above code will be:
John lives in London.