DEV Community

Cover image for PHP Static Methods & Properties
AI_Dosage
AI_Dosage

Posted on • Edited on

2 1

PHP Static Methods & Properties

Static Methods

Static methods can be called directly - without creating an instance of the class first.
Static methods are declared with the static keyword:

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}
// Call static method
greeting::welcome();
?>
Enter fullscreen mode Exit fullscreen mode

A static method can be accessed from a method in the same class using the self keyword and double colon (::):

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }

  public function __construct() {
    self::welcome();
  }
}

new greeting();
?>
Enter fullscreen mode Exit fullscreen mode

Static methods can also be called from methods in other classes. To do this, the static method should be public:

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}

class SomeOtherClass {
  public function message() {
    greeting::welcome();
  }
}
?>
Enter fullscreen mode Exit fullscreen mode

To call a static method from a child class, use the parent keyword inside the child class. Here, the static method can be public or protected.

<?php
class Name{
  protected static function getName() {
    return "Bazeng";
  }
}

class SayName extends Name {
  public $name;
  public function __construct() {
    $this->name= parent::getName();
  }
}

$name= new SayName;
echo $name ->name;
?>
Enter fullscreen mode Exit fullscreen mode
Static properties

Static properties are declared with the static keyword they can be called directly - without creating an instance of a class.Example:

<?php
class Person{
   public static $name = "Bazeng";
 }
echo Person::$name;
Enter fullscreen mode Exit fullscreen mode

To access a static property in a method in same class use self

<?php
class Person{
   public static $name = "Bazeng";
   public function sayName(){
     echo self::$name;
   }
 }

 $person = new Person();
 $person->sayName();

Enter fullscreen mode Exit fullscreen mode

To access a static property in a method in a parent class use parent

<?php
class Person{
   public static $name = "Bazeng";

 }
class SayName extends Person{
   public function __construct(){
    echo parent::$name;
   }
} 

$person = new SayName();
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more