Thursday, 20 May 2021

Php: new self() vs new static()

‘new self()’ statement return an instance of the class in which this statement is actually written.

 

‘new static()’ can be used to define an instance of this class or any derived classes of this class. ‘new static()’ statement is resolved at runtime and refers to whatever class in the hierarchy you called the method on.

 

Let’s see it with an example.

 

new_static_vs_new_self_demo.php

#!/usr/bin/php

<?php
    class MyClass{
        public static function get_instance_using_static(){
            return new static();
        }

        public static function get_instance_using_self(){
            return new self();
        }

        public function about_me(){
            echo "I am an instance of MyClass\n";
        }
    }

    class MyChildClass extends MyClass{
        public function about_me(){
            echo "I am an instance of MyChildClass\n";
        }
    }

    echo "Creating instances using new static()\n";
    $obj1 = MyClass::get_instance_using_static();
    $obj2 = MyChildClass::get_instance_using_static();
    $obj1->about_me();
    $obj2->about_me();

    echo "\nCreating instances using new self()\n";
    //Both the statements return an instance of MyClass
    $obj1 = MyClass::get_instance_using_self();
    $obj2 = MyChildClass::get_instance_using_self();
    //Both print the message 'I am an instance of MyClass'
    $obj1->about_me();
    $obj2->about_me();
    
?>

Output

$./new_static_vs_new_self_demo.php 

Creating instances using new static()
I am an instance of MyClass
I am an instance of MyChildClass

Creating instances using new self()
I am an instance of MyClass
I am an instance of MyClass

 

$obj1 = MyClass::get_instance_using_self();

$obj2 = MyChildClass::get_instance_using_self();

Since 'new self()' resolved at compile time, both the statements return an instance of MyClass.

 

$obj2 = MyChildClass::get_instance_using_static();

Since 'new static()' is resolved at run time, it return an instance of MyChildClass.

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment