PHP static Keyword

❮ PHP Keywords

Example

Create and use static properties and methods:

<?php
class MyClass {
  public static $str = "Hello World!";

  public static function hello() {
    echo MyClass::$str;
  }
}

echo MyClass::$str;
echo "<br>";
echo MyClass::hello();
?>
Try it Yourself »

Definition and Usage

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class.

The static keyword is also used to declare variables in a function which keep their value after the function has ended.


Related Pages

Read more about static methods in our PHP OOP - Static Methods Tutorial.

Read more about static properties in our PHP OOP - Static Properties Tutorial.


More Examples

Example

Use a static variable in a function:

<?php
function add1() {
  static $number = 0;
  $number++;
  return $number;
}

echo add1();
echo "<br>";
echo add1();
echo "<br>";
echo add1();
?>
Try it Yourself »

❮ PHP Keywords
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.