Basics Of Object Oriented Programming Php 2022

    By: Thad Mertz
    2 years ago
    Category: PHPViews: 37


    PHP doesn't support multiple inheritance what is the alternative.

    No, But we can use Interfaces and Traits to achieve the same goal in php.



    Interface in PHP

    We can define interface in pp using keyword interface as given here.

    <?php
      interface InterfaceName {
        public function firstMethod();
        public function secondMethod($name, $color);
        public function thirdMethod() : string;
      }
    ?>		
    
    1. Interfaces cannot have properties.
    2. All interface methods must be public.
    3. Methods in an interface are abstract, so they cannot be implemented in code. Means functions without body.
    4. A class can implement multiple interfaces.
    5. Methods defined in interface must be called in class where interface implemented.



    Abstract in PHP

    We can define abstract classes in php. The main thing is abstract class cannot be instantiated only can be extended. And will have at least one abstract method.

    <?php
    abstract class ParentClass {
      abstract public function someMethod1();
      public function someMethod2($name, $color){
          return $name.'-'.$color;   
        };
      abstract public function someMethod3() : string;
     }
    ?>
    
    1. Abstract class must have at least one abstract method.(abstract method = will have prefix keyword abstract and this function will be without body).
    2. Abstract class can have functions with body, If abstract keyword not applied to function.
    3. Abstract classes cannot be instantiated. Only can be extended.
    4. Abstract classes can have properties. and also can have access modifiers (Public, Protected, Private).
    5. A class can extend only one abstract class at a time.
    6. Only Abstract Methods from abstract class must be called in child class, Non abstract methods are optional and can be called.


    Traits in PHP

    In php we do not have multiple inheritance. One class can extend from only one another class. So in this case we can use Traits. Methods defined in Traits can be used in Multiple classes.

    // Defining a Trait.
    
    <?php
      trait MyTrait {
        // some code...
      }
      
      trait YourTrait{
        // some code...
      }
    ?>
    

    Now to use a trait you can call it as given below

    <?php
    class MyClass {
      use MyTrait, YourTrait;
    }
    ?>
    

    Note we are using multiple traits in class so class have access to methods from both Traits. Here is how you call functions from traits.

    <?php
    trait MyTrait {
      public function message() {
          echo "OOP is Awesome! ";
        }
    }
      
    class Code {
        use MyTrait;
    }
      
    $obj = new Code();
    $obj->message();
    ?>