Differences between static properties and constants

Static properties are properties linked to the class and not a particular object, which means they can be accessed without instantiating them. 
It is possible to reference static properties with a variable:


class Parent {
public static $static_property;
}

Static methods are called using the Scope Resolution Operator (::) .

Inside of the class we would call it with self::


class Parent{
public static $static_property;
    
public function returnStaticPropertyValue() { 
    self::$static_property;        
    }
}

Outside of the class we would call it with the name of the class
class Child {
$child_inherited_static_property = Parent::$static_property;
}

Constants are an identifier for a simple value. For example, the value of number π of or the value of the garvity. They are declared starting with an underscore or letter, in capitals, without the $ sign or using the method define() as follows.

class Parent {
//Either
const GRAVITY = 9.8;
//Or
define ("GRAVITY", "9.8");
}

To call these, same as in the case of static properties, we do it using the Scope Resolution Operator (::), but without the $ sign. 


//Inside of the class
class Parent {
//define the constant
const GRAVITY = 9.8;
//call the constant
public function returnConstantValue {
    self::Gravity;
    }
}
//Outside of the class
class Child {
$child_inherited_constant = Parent::GRAVITY;
}

Apart from they different way in which they are declared and called, is there any other remarkable difference between them? Yes, indeed. Constants value cannot be changed during execution time.


Comments

Popular posts from this blog

SOLID: The Single-Responsibility Principle (SRP)

Symfony HTTP client

Inheritance: Abstract classes and interfaces