Monday, 17 May 2021

Php: static methods

 

Static methods are associated with the class.

 

How to define a static method?

Using ‘static’ keyword you can define a static property.

 

Syntax

static function function_name(args){

 

}

 

Example

static function about_class(){

 

}

 

How to access static properties?

Syntax

ClassName::method_name(args);

 

Example

Employee::about_class();

 

How to access the static methods inside the class?

Syntax

self:: method_name(args);

 

Example

self::about_class();

 

Can I apply access specifiers/visibility modifiers to static methods?

Yes, you can do.

 

Example

private static function about_class(){

 

}

 

public static function print_about_me(){

         

}

 

Find the below working application.

 

static_methods_demo.php

#!/usr/bin/php

<?php

    class Employee{
        public static $organization_name = 'ABC Corp';
        private static $total_employees = 100;

        private static function about_class(){
            $org_name = self::$organization_name;
            $total_emps = self::$total_employees;

            return "org name : $org_name \ntotal_emps : $total_emps";
        }

        public static function print_about_me(){
            $about_this_class = self::about_class();
            echo $about_this_class;
        }
    }

    Employee::print_about_me();
   
?>

 

Output

$./static_methods_demo.php 

org name : ABC Corp 
total_emps : 100

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment