PHP - Class Static properties and methods

Introduction

PHP can define properties and methods linked to the class itself rather than to the object.

These properties and methods are defined with the keyword static.

class My{
     private static $lastId = 0; 

     public static function getLastId(): int { 
        return self::$lastId; 
     } 
}

You can reference it either using the class name or an existing instance, from anywhere in the code:

Demo

<?php
class My{/*w w w .j a v  a 2  s . com*/
     private static $lastId = 0; 

     public static function getLastId(): int { 
        return self::$lastId; 
     } 
}
     
$myInstance = new My();
print(My::getLastId()); 
echo '\n';
print($myInstance::getLastId()); 
?>

Result

Related Topics