PHP 5: const vs static
Asked Answered
O

8

194

In PHP 5, what is the difference between using const and static?

When is each appropriate? And what role does public, protected and private play - if any?

Odlo answered 6/11, 2009 at 7:10 Comment(0)
L
213

In the context of a class, static variables are on the class scope (not the object) scope, but unlike a const, their values can be changed.

class ClassName {
    static $my_var = 10;  /* defaults to public unless otherwise specified */
    const MY_CONST = 5;
}
echo ClassName::$my_var;   // returns 10
echo ClassName::MY_CONST;  // returns 5
ClassName::$my_var = 20;   // now equals 20
ClassName::MY_CONST = 20;  // error! won't work.

Public, protected, and private are irrelevant in terms of consts (which are always public); they are only useful for class variables, including static variable.

  • public static variables can be accessed anywhere via ClassName::$variable.
  • protected static variables can be accessed by the defining class or extending classes via ClassName::$variable.
  • private static variables can be accessed only by the defining class via ClassName::$variable.

Edit: It is important to note that PHP 7.1.0 introduced support for specifying the visibility of class constants.

Letreece answered 6/11, 2009 at 7:14 Comment(5)
I prefer to use self::$variable for protected static and private static variables since I prefer to keep the class name mentioned only once within itself which is at the very beginning of the class.Born
Yes, good point, I neglected to mention that the self keyword can be used if referencing from within the class itself. The examples I provided above were performed outside the class definition, in which case the class name must be used.Letreece
Great answer, very close to accepting. Could you please clarify one point: "Public, protected, and private are irrelevant in terms of consts" - Why? Are consts by default all public? all private?Odlo
does a static var not need a $ ? static $my_var = 10; in the definitionRecall
Old thread, but I would like to add something: check out php.net/manual/en/…, which explains static variables are very useful in singletons and recursive functions as well. Because you CAN change the value but the variable will only be initialized once. See #203836 for further explanation how to create a singleton. For me those are some situations in which I prefer static variables.Split
S
20

One last point that should be made is that a const is always static and public. This means that you can access the const from within the class like so:

class MyClass
{
     const MYCONST = true;
     public function test()
     {
          echo self::MYCONST;
     }
}

From outside the class you would access it like this:

echo MyClass::MYCONST;
Sandfly answered 4/3, 2010 at 1:57 Comment(2)
is that declaration true? that "const is always static and public" ?Bethanie
This is no longer true. As of PHP 7.1 class constants can be declared private or protected. See RFCFeminacy
U
13

Constant is just a constant, i.e. you can't change its value after declaring.

Static variable is accessible without making an instance of a class and therefore shared between all the instances of a class.

Also, there can be a static local variable in a function that is declared only once (on the first execution of a function) and can store its value between function calls, example:

function foo()
{
   static $numOfCalls = 0;
   $numOfCalls++;
   print("this function has been executed " . $numOfCalls . " times");
}
Uticas answered 6/11, 2009 at 10:49 Comment(0)
B
11

When talking about class inheritance you can differentiate between the constant or variable in different scopes by using self and static key words. Check this example which illustrates how to access what:

class Person
{
    static $type = 'person';

    const TYPE = 'person';

    static public function getType(){
        var_dump(self::TYPE);
        var_dump(static::TYPE);

        var_dump(self::$type);
        var_dump(static::$type);
    }
}

class Pirate extends Person
{
    static $type = 'pirate';

    const TYPE = 'pirate';
}

And then do:

$pirate = new Pirate();
$pirate::getType();

or:

Pirate::getType();

Output:

string(6) "person" 
string(6) "pirate" 
string(6) "person" 
string(6) "pirate"

In other words self:: refers to the static property and constant from the same scope where it is being called (in this case the Person superclass), while static:: will access the property and constant from the scope in run time (so in this case in the Pirate subclass).

Read more on late static binding here on php.net.
Also check the answer on another question here and here.

Bonnell answered 24/6, 2015 at 16:4 Comment(0)
P
4

Declaring a class method or property as static makes them accessible without needing an instantiation of the class.

A class constant is just like a normal constant, it cannot be changed at runtime. This is also the only reason you will ever use const for.

Private, public and protected are access modifiers that describes who can access which parameter/method.

Public means that all other objects gets access. Private means that only the instantiated class gets access. Protected means that the instantiated class and derived classes gets access.

Prosy answered 6/11, 2009 at 7:17 Comment(0)
S
2

So to recap on @Matt great answer:

  • if the property you need should not be changed, then a constant is the the proper choice

  • if the property you need is allowed to be changed, use static instead

Example:

class User{
    private static $PASSWORD_SALT = "ASD!@~#asd1";
    ...
}

class Product{
    const INTEREST = 0.10;
    ...
}

Edit: It is important to note that PHP 7.1.0 introduced support for specifying the visibility of class constants.

Sapid answered 17/12, 2013 at 10:6 Comment(0)
P
2

Here's the things i learned so far about static members , constant variables and access modifiers(private,public and protected). Constant

Definition

Like the name says values of a constant variable can't be changed.Constants differ from normal variables in that you don't use the $ symbol to declare or use them.

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.

Note : The variable's value can not be a keyword (e.g. self, parent and static).

Declaring a constant in php

<?php
class constantExample{

   const CONSTANT = 'constant value'; //constant

 }
?>

Constant's scope is global and can be accessed using a self keyword

<?php
class MyClass
{
    const CONSTANT = 'constant value';

    function showConstant() {
        echo  self::CONSTANT . "\n";
    }
}

echo MyClass::CONSTANT . "\n";

$classname = "MyClass";
echo $classname::CONSTANT . "\n"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::CONSTANT."\n"; // As of PHP 5.3.0

?>

Static

Definition

Static keyword can be used for declaring a class, member function or a variable.Static members in a class is global can be accessed using a self keyword as well.Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can). If no visibility declaration ( public, private, protected ) is used, then the property or method will be treated as if it was declared as public.Because static methods are callable without an instance of the object created.

Note : the pseudo-variable $this is not available inside the method declared as static.Static properties cannot be accessed through the object using the arrow operator ->

As of PHP 5.3.0, it's possible to reference the class using a variable. The >variable's value cannot be a keyword (e.g. self, parent and static).

Static property example

<?php
class Foo
{
    public static $my_static = 'foo'; //static variable 

    public static function staticValue() { //static function example
        return self::$my_static;  //return the static variable declared globally
    }
}

?>

Accessing static properties and functions example

 <?php
     print Foo::$my_static . "\n";

    $foo = new Foo();
    print $foo->staticValue() . "\n";
    print $foo->my_static . "\n";      // Undefined "Property" my_static 

    print $foo::$my_static . "\n";
    $classname = 'Foo';
    print $classname::$my_static . "\n"; // As of PHP 5.3.0

    print Bar::$my_static . "\n";
    $bar = new Bar();
    print $bar->fooStatic() . "\n";

 ?>

Public, private , protected (A.K.A access modifiers)

Before reading the definition below , read this Article about Encapsulation .It will help you to understand the concept more deeply

Link 1 wikipedia

Tutorials point link about encapsulation

Definition

Using private , public , protected keywords you can control access to the members in a class. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

Example

 <?php 
class Example{
 public $variable = 'value'; // variable declared as public 
 protected $variable = 'value' //variable declared as protected
 private $variable = 'value'  //variable declared as private

 public function functionName() {  //public function
 //statements
 }

 protected function functionName() {  //protected function
 //statements
 }
  private function functionName() {  //private function
   //statements
   }

} 
 ?> 

Accessing the public, private and protected members example

Public variable's can be accessed and modified from outside the class or inside the class. But You can access the private and protected variables and functions only from inside the class , You can't modify the value of protected or Public members outside the class.

  <?php 
  class Example{
    public $pbVariable = 'value'; 
    protected $protVariable = 'value'; 
    private $privVariable = 'value';
    public function publicFun(){

     echo $this->$pbVariable;  //public variable 
     echo $this->$protVariable;  //protected variable
     echo $this->privVariable; //private variable
    }

   private function PrivateFun(){

 //some statements
  }
  protected function ProtectedFun(){

 //some statements
  }

  }


 $inst = new Example();
 $inst->pbVariable = 'AnotherVariable'; //public variable modifed from outside
 echo $inst->pbVariable;   //print the value of the public variable

 $inst->protVariable = 'var'; //you can't do this with protected variable
 echo $inst->privVariable; // This statement won't work , because variable is limited to private

 $inst->publicFun(); // this will print the values inside the function, Because the function is declared as a public function

 $inst->PrivateFun();   //this one won't work (private)
 $inst->ProtectedFun();  //this one won't work as well (protected)

  ?>

For more info read this php documentation about visibility Visibility Php Doc

References : php.net

I hope you understood the concept. Thanks for reading :) :) Have a good one

Paternoster answered 7/8, 2015 at 14:16 Comment(0)
T
0

i would like you focus on one case different in using self:: and static:: it is also help for debuging to be aware:

<?php
    class ClassTwo extends ClassName {
       const MY_CONST = 3;
    }
    class ClassName {
        const MY_CONST = 5;
        static function check():int { 
            return static::MY_CONST;  // static:: using last lvl parental MY_CONST
        }
        static function check2():int { 
            return self::MY_CONST;  // self:: exactly this class MY_CONST
        }
    }
    echo ClassTwo::MY_CONST;  // returns 3
    echo ClassTwo::check();  // returns 3
    echo ClassTwo::check2();  // returns 5

?>
Tzar answered 22/6, 2023 at 2:31 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.