Asked  7 Months ago    Answers:  5   Viewed   44 times

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?



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.

Wednesday, March 31, 2021
answered 7 Months ago

Static is for:

class properties or methods as static makes them accessible without needing an instantiation of the class

So, the value returned by a static member may differ. For example, you can call a static method with different result depending of what parameters you pass to it.

Constants value:

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

So, it always return the same result when you call it

About create an object and extending a class, when you "create an object" you make an instance of a class. When you extend a class, you create an other class who:

inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.

I hope it help you.

Wednesday, March 31, 2021
answered 7 Months ago

Check this chart :)

alt text

grabbed from this article

Saturday, May 29, 2021
answered 5 Months ago

As I mentioned in the comment, this is more a software design question than a question how to achieve this with PHP.

A static property is not part of the state of an object and will therefore not being serialized with it.

I'll give you a short example how I would solve a related problem. Imagine you have the following message class, that has a static $id property to make sure all instances have a unique id:

class Message {

    public static $id;

    public $instanceId;

    public $text;

    public function __construct($text) {
        // the id will incremented in a static var
        if(!self::$id) {
            self::$id = 1;
        } else {

        // make a copy at current state
        $this->instanceId = self::$id; 
        $this->text = $text;

Serialization / Unserialization code:

$m1 = new Message('foo');
printf('created message id: %s text: %s%s',
    $m1->instanceId,  $m1->text, PHP_EOL);
$m2 = new Message('bar');
printf('created message id: %s text: %s%s',
    $m2->instanceId,  $m2->text, PHP_EOL);

$messages = array($m1, $m2);

$ser1 = serialize($m1);
$ser2 = serialize($m2);

$m1 = unserialize($ser1);
printf('unserialized message id: %s text: %s%s',
    $m1->instanceId,  $m1->text, PHP_EOL);
$m2 = unserialize($ser2);
printf('unserialized message id: %s text: %s%s',
    $m2->instanceId,  $m2->text, PHP_EOL);

To make sure that the id is unique across multiple script runs further work is nessary. You'll have to make sure that Message::$id is initialized before any object creation, using the value from last script run. This will get additionally wired when it comes to parallel PHP request on a webserver.

Its just an example with the simplest static property I know: an instance counter. In this case I would do so. But I hope you see that there is further work required to serialize / unserialize static properties without have side effects. And this depends on your application needs.

This question cannot be answered general I tend to say it makes no sense in any case to serialize static members. But I would appreciate comments on this.

Saturday, May 29, 2021
answered 5 Months ago

As long as we are talking about declaring compile-time constants of scalar integer or enum types, there's absolutely no difference between using const (static const in class scope) or constexpr.

Note that compilers are required to support static const int objects (declared with constant initializers) in constant expressions, meaning that they have no choice but to treat such objects as compile-time constants. Additionally, as long as such objects remain odr-unused, they require no definition, which further demonstrates that they won't be used as run-time values.

Also, rules of constant initialization prevent local static const int objects from being initialized dynamically, meaning that there's no performance penalty for declaring such objects locally. Moreover, immunity of integral static objects to ordering problems of static initialization is a very important feature of the language.

constexpr is an extension and generalization of the concept that was originally implemented in C++ through const with a constant initializer. For integer types constexpr does not offer anything extra over what const already did. constexpr simply performs an early check of the "constness" of initializer. However, one might say that constexpr is a feature designed specifically for that purpose so it fits better stylistically.

Monday, June 28, 2021
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :