G
G
golova122015-07-16 12:09:30
PHP
golova12, 2015-07-16 12:09:30

Static class properties in PHP?

I had never used them before, but I was very interested in this feature of the . In the past, I've used static methods as little helper functions that don't need an object's context, object state, and so on to work. (or create helper classes consisting only of static methods). But why did they introduce static properties, and even with the ability to make them private? In fact, it turns out an object without an object. which can set the state and read it in the same way as a normal object created with new , with the only difference that it does not have a constructor and some more features:

<?php

class StaticClass
{
    private static $property;

    public static function setProp($value)
    {
        self::$property = $value;
    }

    public static function getProp()
    {
        $prop = self::$property;

        return self::doSomething($prop);
    }

    private static function doSomething($arg)
    {
        // что-то делаем
        return $arg;
    }
}

StaticClass::doSomething(1); // нельзя
StaticClass::$property = 1; // нельзя

StaticClass::setProp(2);
StaticClass::getProp(); // 2

I would like to understand how to use this feature and how static variables affect performance and memory consumption?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Litvinenko, 2015-07-16
@edli007

Apparently you have not worked with patterns. The essence of statics is that such a property will be common to all objects of this class.
Read about the singleton, after a couple of days, as you figure it out, all questions will disappear.

M
Marcuzy, 2015-07-16
@Marcuzy

When an entity is only needed in one instance, what's the point of creating an object?
A very simple example is helpers ( Array Helper ). You just connect a helper and get a set of functions united by a common goal in one entity - this improves the semantics of the code + OOP goodies, such as inheritance.
Private properties - quite a feature, what confuses you? If a class has utility static methods and attributes that should only be accessible from other static methods of that class, the same parsley as with regular methods/attributes.
Another useful application of static methods is the Factory Method pattern.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question