PHP OOP - Static Properties

PHP - Static Properties


A static property:

  • Belongs to the class itself, not any object instance.
  • Is shared across all instances of the class.
  • Static properties are declared with the static keyword:
  • Can be accessed using the ClassName::$propertyName or self::$propertyName from within the class.


Syntax


<?php
  class ClassName {
    public static $staticProp = "W3Schools";
  }
?>


To access a static property use the class name, double colon (::), and the property name:


Syntax


ClassName::$staticProp;


Let's look at an example:

Example
<?php
class MyClass {
public static $name = "PHP";
}
echo MyClass::$name; // Output: PHP
?>

Try it yourself

Explanation:

  • public static $name = "PHP";

Declares a static property called $name that belongs to the class MyClass.

  • MyClass::$name

Outside the class, you use the class name with :: to access static properties or methods.

  • You don’t need to create an object to access static members. That’s the beauty of static.


PHP - More on Static Properties


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

Example
<?php
class MyClass {
public static $name = "PHP";
public static function getName() {
return self::$name;
}
}
echo MyClass::$name; // Output: PHP
echo MyClass::getName(); // Output: PHP
?>

Try it yourself

Explanation:

  • public static $name = "PHP";

Declares a static property called $name that belongs to the class MyClass.

  • self::$name

Inside the class, you use self:: to refer to static members.

  • MyClass::$name

Outside the class, you use the class name with :: to access static properties or methods.

To call a static property from a parent class using the parent keyword inside the child class.

Example
<?php
class MyClass {
public static $name = "PHP (Parent)";
}
class MyChild extends MyClass {
public static function getParentName() {
return parent::$name; // Accesses parent's $name
}
}
// Output
echo MyClass::$name . "<br>"; // PHP (Parent)
echo MyChild::getParentName() . "<br>"; // PHP (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.