PHP OOP - Classes and Objects
A class is a template for objects, and an object is an instance of class.
Define a Class
A class is the user-defined data type combines variables, local data, and functions. A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods go inside the braces:
class Language {
// code goes here...
}
?>
Below we declare a class named product consisting of two properties ($productname and $price) and two methods set_name() and get_name() for setting and getting the $product property:
Example - define class
Define Objects
These are local instances created by the developer to access the content of the class. Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.
Objects of a class is created using the new keyword.
In the Example below, $apple and $banana are instances of the class Fruit:
Example - define objects
PHP - The $this Keyword
The $this keyword refers to the current object, and is only available inside methods.
1. Inside the class (by adding a set_name() method and use $this):
2. Outside the class (by directly changing the property value):
PHP - instanceof
The instanceof keyword is to check if an object belongs to a specific class: