Tuesday, 18 May 2021

Php: new self(): Return instance of the class where new statement is defined

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

 

Let’s see it with an example.

 

new_self_demo.php

#!/usr/bin/php

<?php
    class MyClass{
        public static function get_instance(){
            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";
        }
    }

    $obj1 = MyClass::get_instance();
    $obj2 = MyChildClass::get_instance();

    //Both print the message 'I am an instance of MyClass'
    $obj1->about_me();
    $obj2->about_me();
    
?>

 

Output

$./new_self_demo.php 

I am an instance of MyClass
I am an instance of MyClass

 

As you see above snippet, I created an instance of MyClass, MyChildClass using get_instance() method. Since this method uses ‘new self()’ method to create an instance, it always return an instance of MyClass. You can confirm the same using program output.

 

$obj1 = MyClass::get_instance();

$obj2 = MyChildClass::get_instance();

Both the statements return an instance of MyClass.


 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment