PHP OOP - Static Methods

PHP - Static Methods


In PHP, static methods belong to the class itself, not to a specific object of the class. 


You can call a static method without creating an object.


Static methods are declared with the static keyword:


Syntax


class ClassName {
  public static function staticMethodName() {
    // code
  }
}


You call the method using the class name, double colon (::), and the method name::


Syntax


ClassName::staticMethodName();



Let's look at an example:

Example
<?php
class Greeting {
public static function welcome() {
return "Welcome to PHP Static Methods!";
}
}
// Call the static method without creating an object
echo Greeting::welcome();
?>

Try it yourself

Explanation:


  • public static function welcome() → Declares a static method.
  • Greeting::welcome(); → Calls the method without creating an object.

PHP - More on Static Methods


 In PHP, a class can contain both static and non-static methods. Static methods can be accessed from within the same class using the self:: keyword (with the scope resolution operator ::).

Example
<?php
class Greeting {
public static function welcome() {
echo "Welcome to PHP Static Methods!";
}
public function __construct() {
self::welcome();
}
}
new Greeting();
?>

Try it yourself

In PHP, public static methods can be accessed from outside their class, including from other classes.

Example
<?php
class Helper {
// Public static method
public static function greet($name) {
return "Hello, $name!";
}
}
class User {
public function sayHello($username) {
// Calling static method from Helper class
return Helper::greet($username);
}
}
// Create object of User class
$user = new User();
echo $user->sayHello("Alice"); // Output: Hello, Alice!
?>

Try it yourself

In PHP, when you're working with inheritance, you can call a static method from a parent class inside a child class using the parent:: keyword. This works for public and protected static methods.

Example
<?php
class ParentClass {
protected static function showMessage() {
return "Hello from Parent!";
}
}
class ChildClass extends ParentClass {
public static function callParentMethod() {
return parent::showMessage();
}
}
echo ChildClass::callParentMethod(); // Output: Hello from Parent!
?>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.