Introduction
In this article we learn the basic concepts of Object Oriented Programming in PHP. This article covers Object Oriented Programming conecepts that are used in PHP. This articles covers the following topics.
- Class
- Create variables for a class
- Create function for a class
- Class constructor
- Instantiate a class
- creating class constructor
- Variable and method call using objects
- Constructor and Destructor
- visibility
- Object Inheritance
- Scope Resolution Operator
- Overloading
- Late static Binding
Class
A Class is a template; a template for an Object. Let's understand this by an example, you have seen many times Humans, a shop, a house, a ground, a shirt, t-shirts and many more things. These are all examples of classes. Let's understand how they become an object. Suppose a human is class then Rajeev is an object of that class as in the following:
Ground: cricket ground , hockey ground, football ground, and so on.
Animal: cow, dog, elephants ...
The following is an examle of creating a class in PHP:
To create a class in PHP we should use the class keyword and then a <className>. This className is the programmer's choice depending on their needs, and opening and closing braces.
Create variables for a classA class variable is known as properties, these variables can store values and these values are important information for your class. So we can say that class variables are class properties.
Example
- class student{
- var $rollNo;
- var $name;
- var $address;
- }
In this code above, $rollNo, $name and $address are the class variables.
Note: When you are declare any class variable you should always use the "var" keyword in PHP.
Create Methods for class Class methods or functions are like regular functions, the only difference is they are inside the class. In simple words class functions are known as, or called, "Methods". These methods are used for retrieving the data or manipulating the data. In the following example I am trying to demonstrate the class methods.
- class student{
- var $rollNo;
- var $name;
- var $address;
- function Display(){
-
-
- }
- function AddStudent(){
-
- }
- }
Instantiate a classLet's understand the meaning of "instantiation". In general programming words , " The process of creating an Object is known as as instantiation". The new keyword is used to create an object of that class. The new keyword and the name of the class to instantiate from. Let's see the syntax and an example.
Syntax$objName = new className();
Example$ObjStudentName = new student();
Creating a class constructorLet's understand what a constructor is before trying to understand the creation process. Suppose you want an object to have some value (certain) when you instantiate that object. If you want records of student to be initialized after the object creation then that is what the class constructor is used for. The __construct() function calls the constructor in PHP.
Syntaxvoid __construct( [ mixed $args = "" [ , $ . . . ] ] )
Example
- class student{
- var $rollNo;
- var $name;
- var $address;
- function __construct(){
- $this->$rollNo=101;
- $this->$name='rajeev';
- $this->$address='pune';
- }
- }
Variable and method call using objectsIn this topic we will see how we reference the class variable and methods in PHP.
Syntax
$object -> variable;
$object -> function();
Example
$ObjStud -> name;
$ObjStud -> AddStudent();
- <?php
- class student{
- var $rollNo;
- var $name;
- var $address;
- function display($rNo, $Nam, $Add){
- $rollNo=$rNo;
- $name=$Nam;
- $address=$Add;
- echo "Roll No -" .$rollNo. "<br/>";
- echo "Name - " .$name. "<br/>";
- echo "Address - " .$address. "<br/>";
- }
- function __construct($rNo, $Nam, $Add){
- $rollNo=$rNo;
- $name=$Nam;
- $address=$Add;
- echo "Constructor is called <br/>";
- echo "Roll No -" .$rollNo. "<br/>";
- echo "Name - " .$name. "<br/>";
- echo "Address - " .$address. "<br/>";
-
- }
- }
- $ObjStud = new student("101","rajeev","New Delhi");
- echo "-------------------------------<br/>";
- $ObjStud->display("102","ranjan","New Delhi");
- ?>
Constructor and Destructor
A constructor is a function that is executed after the object has been initialized. Initialized means its memory allocation, instance, properties and so on. Its purpose is to put the object in a valid state. Usually, an object is always in a usable state, requiring some data. The purpose of the constructor is to force this data to be given to the object at instantiation time and disallow any instances without such data.
The __construct() method is used for the constructor.
Let us consider a simple class that encapsulates a string and has a method that returns the length of this string.
- <?php
- class constructorTest{
- private $str;
- public function strString($str){
- $this->str= (string) $str;
- }
- public function getLength(){
- if($this->str===null){
- throw new RuntimeException(" Invalid state");
- }
- return strlen($this->str);
- }
- }
- ?>
In order to be a valid state of code, this function requires setString to be called before getLength. This can only happen using the constructor.
- class constructorTest{
- private $str;
- public function __construct($str){
- $this->str- (string) $str;
- }
- public function getLength(){
- return strlen($this->str);
- }
- }
A Destructor is called when an object is about to be freed from memory. In general words a destructor has cleanup code to destroy the object instance. PHP cleans all the resources held by the script when the script execution ends.
The __destructor() method is used to destroy the free resources, like files, databases and so on.
Visibility
Visibility in PHP determines how your class members can be accessed. There are mainly the 3 types of visibility access in PHP, they are public, private and protected.
- Private Member: Can only be accessed from inside the class itself.
- Protected Member: Can only be accessed from inside the class itself and its child classes.
- Public Member: Can be accessed from anywhere, outside, inside, in a child class, everywhere.
Object InheritanceInheritance is the ability to derive new classes from existing classes. A derived class (or sub class) inherits the instance variables and methods of the base class (or superclass) and they (may) add new instance variables and methods. New methods may be defined with the same name as those in the base class; this process, known as overriding. extends the keyword to the use of inheriting the base class. In the following example we demonstrate the concepts of Inheritance with a simple example.
- <?php
- class A
- {
- public $public = 'Public Access Modifier';
- protected $protected = 'Protected Access Modifier';
- private $private = 'Private Access Modifier';
-
- function printHello()
- {
- echo $this->public;
- echo $this->protected;
- echo $this->private;
- }
- }
-
- $obj = new A();
- echo $obj->public;
- echo $obj->protected;
- echo $obj->private;
- $obj->printHello();
-
- class B extends A
- {
-
- protected $protected = 'Protected2 Access Modifier';
-
- function printHello()
- {
- echo $this->public;
- echo $this->protected;
- echo $this->private;
- }
- }
-
- $obj2 = new B();
- echo $obj2->public;
- echo $obj2->protected;
- echo $obj2->private;
- $obj2->printHello();
- ?>
Scope Resolution Operator
The Scope resolution operator (
::) defines a function outside a class or when we want to use a global variable but also have a local variable with the same name. Scope Resolution Operator (
::) is a token that allows access to static, constant and overridden properties or methods of a class. When we reference these items from the class definition, use the name of the class.
OverloadingPHP's overloading is different than other Object Oriented languages. Overloading provides the ability to have multiple methods with the same name but various quantities and types of arguments and their return types. In PHP, however, overloading allows the dynamic creation of properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types. The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope.
Property Overloading
- public void __set( string $name, mixed $value ): Run when writing data to inaccessible properties.
-
- public mixed __get ( string $name): Reading data from inaccessible properties.
- public bool __isset( string $name ): Is triggered by calling isset() or empty() on inaccessible properties.
- public void __unset( string $name): This function is invoked when unset() is used on inaccessible properties.
- <?php
- class PropertyTest
- {
- private $data = array();
- public $declared = 1;
- private $hidden = 2;
-
- public function __set($name, $value)
- {
- echo "Setting '$name' to '$value'\n";
- $this->data[$name] = $value;
- }
-
- public function __get($name)
- {
- echo "Getting '$name'\n";
- if (array_key_exists($name, $this->data)) {
- return $this->data[$name];
- }
- }
-
- public function __isset($name)
- {
- echo "Is '$name' set?\n";
- return isset($this->data[$name]);
- }
-
- public function __unset($name)
- {
- echo "Unsetting '$name'\n";
- unset($this->data[$name]);
- }
- public function getHidden()
- {
- return $this->hidden;
- }
- }
-
- $obj = new PropertyTest;
- $obj->x = 1;
- echo $obj->x . "\n\n";
- var_dump(isset($obj->x));
- unset($obj->x);
- var_dump(isset($obj->x));
- echo "\n";
- echo $obj->declared . "\n\n";
- echo "This is the hidden field property:\n";
- echo "Privates are visible inside the class, so __get() not used...\n";
- echo $obj->getHidden() . "\n";
- echo "Privates not visible outside of class, so __get() is used...\n";
- echo $obj->hidden . "\n";
- ?>
Late static Binding
Late static binding is a variant of binding somewhere between static and dynamic binding. Let us consider the following example:
- class A {
- static $word = "hello world";
- static function hello(){
- print self :: $word;
- }
- class B extends A {
- static $word ="good byee";
- }
- B :: hello();
In this example, the PHP interpreter binds the function hello() to class A so the call to B :: hello() gives the output " hello world". If the self :: $word had been based on late static binding, then the result would be " good byee".
Summary
In this article we learned Object Oriented Programming concepts in PHP, we learned how to make a class in PHP, what the benefits of constructors and destructors are and all other object oriented topics we covered.