PHP OOP - Metode statice. Sintaxă. Exemplu explicat.
Partajeaza in Google Classroom
Memorator: Descriere video Descarcă PDF
PHP - Metode statice
Metodele statice (static methods) pot fi apelate direct - fără a crea o instanță a unei clase.
Metodele statice (static methods) sunt declarate cu ajutorul cuvântului cheie static (static keyword):
Sintaxă
<?php
class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
?>
Pentru a accesa o metodă statică (static method), folosiți numele clasei (class name), dublul punct (::) și numele metodei (method name):
Sintaxă
ClassName::staticMethod();
Exemplu:
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}
// Apelare metoda statică (static method)
greeting::welcome();
?>
Exemplu explicat
Aici, declarăm o metodă statică (static method): welcome(). Apoi, apelăm metodă statică (static method) folosind numele clasei (class name), dublul punct (::) și numele metodei (method name) (fără a crea mai întâi o clasă).