Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How self is different from $this in php.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 113
    Comment on it

    Hello reader's lets discuss "How self is different from $this in php".

    Generally, we can claim that $this is used to reference the current object, whereas self is used to access the current class itself. yet there are many things and details about self and $this that I can identify below, which you should definitely know concerning about. For more understating I am taking a example that will help you to clear the things. We have a class Vehicle and a another class called Car. The Car class overrides the className() function.

    /*Author: Jaydeep*/
    
    <?php
    class Vehicle {
    
         public function className() {
         /*Note that this method is overrides*/
            echo "I am Vehicle!";
        }
    
        public function displayClassName() {
           $this->className();
        }
    }
    
    class Car extends Vehicle {
    
        public function className() {
            echo "I am a Car!";
        }
    
    }
    
    $carObj = new Car();
    $carObj->displayClassName();
    

    output will be:
    I am a car!


    In this example I have created an object of the car class and named it $carObj. And call displayClassName() function which is Vehicle class function and that function call the className() function which is override by car class. Now see both class have className() function but it call's to Car class function className(), this is because $this define always the reference of current object, and we are calling function by Car class object.

    Using Self

    <?php
    class Vehicle {
    
         public function className() {
         /*Note that this method is overrides*/
            echo "I am Vehicle!";
        }
    
        public function displayClassName() {
           $self::className();
        }
    }
    
    class Car extends Vehicle {
    
        public function className() {
            echo "I am a Car!";
        }
    
    }
    
    $carObj = new Car();
    $carObj->displayClassName();
    


    output will be:
    I am a Vehicle!

    In above example, I have pointed the output is change, this is because it automatically call the className() function of vehicle class not of Car class.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: