Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Static Properties

PHP – Static Properties

Static properties can be accessed directly without instantiating the class.

They are declared using the static keyword.

Syntax

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

To access a static property, use the class name followed by double colons (::) and the property name.

Syntax

ClassName::$staticProp;

Here’s an example:

Example

<?php
class pi {
  public static $value = 3.14159;
}

// Get static property
echo pi::$value;
?>

Example Explained

In this example, we declare a static property called $value. We then output the value of this static property using the class name, double colon (::), and the property name, without needing to create an instance of the class first.

PHP – More on Static Properties

A class can have both static and non-static properties. To access a static property from a method within the same class, use the self keyword followed by the double colon (::).

Example

<?php
class pi {
  public static $value=3.14159;
  public function staticValue() {
    return self::$value;
  }
}

$pi = new pi();
echo $pi->staticValue();
?>

To access a static property from a child class, use the parent keyword within the child class.

Example

<?php
class pi {
  public static $value=3.14159;
}

class x extends pi {
  public function xStatic() {
    return parent::$value;
  }
}

// Get value of static property directly via child class
echo x::$value;

// or get value of static property via xStatic() method
$x = new x();
echo $x->xStatic();
?>