Friday 21 May 2021

How to refer parent class properties, methods from sub class

There are two ways to refer parent class data from sub class.

a.   Using the class name directly.

Ex: ClassName::method_name(args)

b.   Using the keyword ‘parent’.

Ex: parent::method_name(args)

 

When can I call parent class methods?

If you override a static method in sub class, and if you want to call the parent class method explicitly, you can use this syntax.

 

parent_keyword_demo.php

#!/usr/bin/php

<?php

    class ParentClass{
       public static function about_me(){
           echo "\n\nI am in parent class";
       }
    }

    class ChildClass1 extends ParentClass{

        public static function about_me(){
            ParentClass::about_me();
            echo "\nI am in ChildClass1";
        }
    }

    class ChildClass2 extends ParentClass{
        public static function about_me(){
            parent::about_me();
            echo "\nI am in ChildClass2";
        }
    }

    ParentClass::about_me();
    ChildClass1::about_me();
    ChildClass2::about_me();

?>

 

Output

#!/usr/bin/php

<?php

    class ParentClass{
       public static function about_me(){
           echo "\n\nI am in parent class";
       }
    }

    class ChildClass1 extends ParentClass{

        public static function about_me(){
            ParentClass::about_me();
            echo "\nI am in ChildClass1";
        }
    }

    class ChildClass2 extends ParentClass{
        public static function about_me(){
            parent::about_me();
            echo "\nI am in ChildClass2";
        }
    }

    ParentClass::about_me();
    ChildClass1::about_me();
    ChildClass2::about_me();

?>

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment