Skip to main content

OOPS in PHP part I

Static Methods and Properties:

Static Methods and Properties is very useful feature in PHP and in this post i am going to tell you about Static Methods and Properties in PHP with example.
If you declare any class property or methods as static then you don't need to create object of class to access that means it can be accessible without creating object of class. You can access directly from class with the help of scope resolution operator (::).
You can use static keyword to define static methods and properties.


class myClass {
    static public $variable1 = 5;
    static public $variable2 = 2;
    static public function getSum() {
        $sum=self::$variable1+self::$variable2;
        print "Sum of two variables is " . $sum;
    }
}

echo myClass::$variable1;
myClass::getSum();
If you extends the parent class in child class and want to access parent class property then you can use parent keyword.

parent::$variable1


Why use static methods and properties?
Now the question is why you will use static methods and properties in your application.



While working with large OOP based project you will have to use many classes and as i told you static methods aren't associated with an instance so from any class you can access the properties of any other class by their class name and you won't need to pass elements of different class manually through each class because static elements can be accessible from anywhere in your application.

Encapsulation : 

Wrapping some data in a single unit is called Encapsulation. Encapsulation is used to save data or information in an object from another it means encapsulation is mainly used for protection purposes.

In the technology era, it is essential to maintain your privacy. So for security reasons, Sometimes we make a private method.

The private method means it can be accessed within the same class. Outside, the Class can't access the private method of other classes. That's why encapsulation is known as data hiding is the main advantage for encapsulation.

The second advantage of encapsulation is you can make the class read-only or write only by providing a setter or getter method.

Polymorphism: 

Polymorphism is a design pattern in which classes have different functionality while sharing a common interface.
 You can define an interface in PHP using interface or abstract classes.


interface Shape {
 public function area();
}
now let's suppose we have different classes, like class circle, class Rectangle,  
class Circle implements Shape {
 public function area() {
 return $this -> radius * $this -> radius * pi();
 }
}
class Rectangle implements Shape {
 public function area() {
 return $this -> width * $this -> height;
 }
}
so all the classes have same function name with different behavious, it's Polymorphism.

Multilevel and Multiple Inheritance in PHP:

PHP OOP does not allow multiple inheritances, it allows only multilevel inheritance.
In simple words, a subclass can not extend more than one superclass.
But PHP allows hierarchical inheritance, Hierarchical inheritance means a child can get property of their parent and parent can get the property of grandparent, so in this way, a child can get also some property of their grandparent.

Interface in PHP : 

An Interface does not contain any functionality, it only specify set of methods which classes must implement.
You can create interface in php oop by using interface keyword.

Properties of Interfaces : 


1 - The classes that implement the interfaces must define all the methods that they inherit from the interfaces, including all the parameters.

2 - All methods declared in an interface must be public; this is the nature of an interface. otherwise, it will generate an error
3 - The class implementing the interface must use the exact same method signatures as are defined in the interface.
4 - Interfaces can be extended like classes using the extends operator.
5 - If we extend the interface all the methods of the interface must be implemented in the child class.
6 - We cannot define a variable in an interface.
Like Below,
 <?php  
 interface A {  
   public function Compute();  
 }  
 interface B extends A {  
   public function Divide();  
 }  
 class C implements B {  
   public function Divide() {  
   echo “division of 10/2 is” . 10/2;  
 }  
   public function Compute() {  
    echo “multiplication of 2*3 is” . $a*$b;  
   }  
 }  

You can implement your interface in classes by using the implements keyword.
If you will use other than public visibility then it will generate an error.


Abstract Classes & Methods :


An abstract class is a class that has at least one abstract method. Abstract methods can only have names and arguments, and no other code.

Thus, we cannot create objects of abstract classes. Instead, we need to create child classes that add the code into the bodies of the methods and use these child classes to create objects.

Features of Abstract Classes :

- only has function name & parameter no body of code,
- Can not create the instance of the abstract class,
If a class has only one method as abstract, then that class must be an abstract class.
- Declaring a class abstract only means that you don't allow it to be instantiated on its own.
The child class which extends an abstract class must define all the methods of the abstract class. it is required. only need to define the methods which are abstract we can leave the other methods.
You can declare your abstract method in child class with the same visibility or less restricted visibility.
- The signatures of the methods must match, 
optional parameter given in the child class will be accepted.
// Abstract class
abstract class Base {
    // This is abstract function
    abstract function printdata(); 
    
//no need to call this function in child class because its not abstract
public function getdata(){
      return "data is ready";
    
}
class Derived extends base {
    function printdata() {
        echo "Derived class";
    }
}
  
// Uncommenting the following line will 
// cause compiler error as the line tries
// to create an instance of abstract class. 
// $b = new Base(); 
      
$b1 = new Derived;
$b1->printdata(); 
 
optional parameter Abstract Class:
 


Differnce between abstract and interfaces:-

  1. Multiple and multilevel both type of inheritance is possible in interface. But single and multilevel inheritance is possible in abstract classes.
  2. Method of php interface must be public only. Method in abstract class in php could be public or protected both.
  3. Interfaces can only have constants and method only While abstract class can have constants, members, method stubs (methods without a body), methods
  4. No need of implementing methods from parent interface when interface is extending another interface, In Abstract Child class must implement all the abstract method of parent class when extend keyword is used.

Comments

Popular posts from this blog

How to span column of custom table in Drupal

If you want to span the column of custom drupal table like below image, Follow the below code to make the header of the table , <?php $header = array('S.N','District', array('data' => '<div class ="house">Household </div><br><span>Rural</span> <p>Urban</p>','colspan' => 2), array('data' => '<div class ="house">Members</div> <br><span>Rural</span> <p>Urban</p>','colspan' => 2), 'Duplicate/Failed Registration', array('data' => '<div class ="house">Pending De duplication </div><br><span>Rural</span> <p>Urban</p>','colspan' => 2), 'Non Un-organised Workers', 'SSID Generated', 'No. of Card Personlised', ); $rows[] = arra...

Drupal 8 : Link actions,Link menus,Link Tasks,Routings

Drupal 8 : Link actions,Link menus,Link Tasks,Routings Link actions Local actions have also been moved out of the hook_menu() system in Drupal 8 .Use actions to define local operations such as adding new items to an administrative list (menus, contact categories, etc). Local actions are defined in a YAML format, named after the module they are defined by. Such as menu_ui.links.action.yml for this example from menu_ui module: menu_ui.link_add:   route_name: menu_ui.link_add   title: 'Add link'   appears_on:     - menu_ui.menu_edit Here, menu_ui.link_add: It is the Unique name of the link action Most likely start with module name, route_name : Name of the route it means when click the link it redirect to this route, appears_on :  An array of route names for this action to be display on. Now how to know the Route name of any internal/external admin pages like below, By through the drupal console we achieve it, drupal debug:router...

Get The field values of node in Drupal 8

use Drupal \ node \ NodeInterface ; /** * Implements hook_ENTITY_TYPE_insert() for node entities. * * This tests saving a node on node insert. * * @see \Drupal\node\Tests\NodeSaveTest::testNodeSaveOnInsert() */ function node_test_node_insert ( NodeInterface $node ) { // Set the node title to the node ID and save. if ( $node - > getTitle ( ) == 'new' ) { $node - > setTitle ( 'Node ' . $node - > id ( ) ) ; $node - > setNewRevision ( FALSE ) ; $node - > save ( ) ; } } Now There is so many functions are there to get the values, For All the functions available visit the API code, https://api.drupal.org/api/drupal/core%21modules%21node%21src%21NodeInterface.php/interface/NodeInterface/8.2.x Some of as below, Node edit form, Drupal 8 Automatically Load the whole object no need to load the entity like below, if ($event->getFormId() == 'node_alexa_audio_clips_edit_form') { $node = \Drupal::ro...