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 »
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.
Read more about static methods in our PHP OOP - Static Methods Tutorial.
Read more about static properties in our PHP OOP - Static Properties Tutorial.
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 »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!