Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - when to use private static properties in the class

Tags:

php

I am learning php and there are still alot of unclear areas for me in the language. I wonder when and why would we use private static properties inside the class. From what I understood private properties may only be accessed by the class where it was defined. So, the private part is clear, but the static is still unclear. In the docs it says:

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).

Does that mean that I can access static properties without instantiation of the class. So, for example:

class Foo{

    static $bar;

    public function __construct($bar){
        $this->bar = $bar;
    }

So, I can access the $bar property of the class like so?

Foo::$bar

But, if I do this, it wouldn't work?

$foo = new Foo();
$foo::$bar

And, then if do make a property private static for which reason would we do that, since I thought we make them static in order to access them outside of their class and making them private would make that impossible. I would be very grateful if someone could clear this up to me.

like image 723
Leff Avatar asked Mar 30 '17 09:03

Leff


1 Answers

When you declare a normal property, there is a different value of that property for every instance you create of that class (each object you create with new Foo). For a static property, there is one copy of that variable for the whole class.

This is separate from the visibility of that variable - a public static property exists once per class, and can be accessed from everywhere; a private static property exists once per class, but can only be accessed from inside that class's definition.

As a simple example, you could have a counter that gave each instance of the class a unique number. You don't need code outside the class to see or change this counter, so you mark it private, but it needs to be shared amongst all instances, so you mark it static.

class Foo {
    // Static counter; shared with every instance
    private static $nextID=0;

    // Normal instance property: each instance will have its own value
    private $myID;

    public function __construct() {
        // Set the ID for this instance to the next ID
        $this->myID = self::$nextID;
        // Increment the shared counter
        self::$nextID++;
    }
}
like image 126
IMSoP Avatar answered Sep 20 '22 05:09

IMSoP