Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it's not possible to use any magic constants in a static context?

Tags:

object

php

static

Is there any particular reason to deny the use of magic constants (like __DIR__) in PHP when in a static context? OOP POV seems nothing is wrong since __DIR__ is "global" that is not instance specific:

class MyClass
{

    protected static $options = array(
            'key1' => 2,
            'key2' => __DIR__ .'/mypic.png' // Triggers a syntax error
    );

    public function __construct() {}

}

EDIT clarification about the question. I'm interested in "why" it's not possible. For example, speaking about static stuff, anyone knows this is not possible:

public static function getName() { return $this->name; }

because getName() is shared across multiple instances and $this->name doesn't make any sense because static function "doesn't know" what instance to refer.

like image 445
gremo Avatar asked Dec 29 '25 11:12

gremo


1 Answers

It isn't the use of __DIR__ or magic constants specifically here that isn't permissible. It is the dynamic construction of anything inside a property definition that isn't allowed. You'd also get a syntax error if you tried to concatenate two atomic strings like "a" . "b" inside a static property definition.

From the docs:

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.... And concatenation, even onto a constant, counts as an expression which isn't allowed.

The PHP manual doesn't specify why initializing static variables with the result of an expression is a parse error, but it is likely due to the fact that static declarations are resolved at compile time, not runtime.

like image 172
Michael Berkowski Avatar answered Jan 01 '26 02:01

Michael Berkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!