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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 99
    Comment on it

    Hello Readers,

    1. We can use the self in static function while this is not.

    2. we can use accessible class variable and methods with self and this are:

    for self self::

    for this $this->

    1. $this needs an instantiated object while self not.

    2. self refers to the class in which it is called, while $this refers to the class of the current object.

    3. self can also turn off polymorphic behavior by bypassing the vtable while $this not

    4. Examples of self anf this :

    Example of self in PHP:

    <?php 
    
    class Car
    {
        public static function model()
        {
             self::getModel();
        }
    
        protected static function getModel()
        {
            echo "I am a Car";
        }
    
    }
    
    ?>
    

    In the above example we use a class Car and make call to the static function in the Car class.

    we use the self::getModel() like

    Car::model();
    

    So the output of the above program will be:

    I am a Car


    Another Example of self and this in PHP:

    <?php
    
    class ParentClass {
        function test() {
            self::who();    // will output 'parent'
            $this->who();  // will output 'child'
        }
    
        function who() {
            echo 'parent';
        }
    }
    
    class ChildClass extends ParentClass {
        function who() {
            echo 'child';
        }
    }
    
    $obj = new ChildClass();
    $obj->test();
    
    ?>
    

    In this example, we use the both self ad this we use self as a (self::who()) will always output (parent)

    while $this used as a ($this->who()) will depend on what class the object has.

 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: