Autor Zpráva
_fantomas
Profil
Dobrý deň, dnes som sa snažil do pola napchať premennú ale cele mi to vypisuje samé chyby.
Chcem sa opýtať prečo nieje možné použiť tento príklad.
    protected static $data = array(
        'description' => '',
        'key_words' => '',
        'user' => $_SESSION['username']
    );

Ako sa to prosím vás dá vyriešiť?
Chyba: syntax error, unexpected '$_SESSION' (T_VARIABLE)
juriad
Profil
_fantomas:
Like any other PHP static variable, static properties may only be initialized using a literal or constant before PHP 5.6; expressions are not allowed. In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.
php.net/manual/en/language.oop5.static.php

V podstatě jde o to, že $_SESSION['username'] není konstanta známá před spuštěním skriptu.

Viz též stackoverflow.com/questions/693691/how-to-initialize-static-variables pro ukázky řešení.
_fantomas
Profil
akože mam spraviť toto?
public static $user = $_SESSION['username'];
Pretože to moc nefunguje.
Keeehi
Profil
Spíš
Class Foo {
    protected static $data;
    
    public static function init() {
        self::data = array(
            'description' => '',
            'key_words' => '',
            'user' => $_SESSION['username']
        );
    }
}

EDIT: opraven překlep, viz [#5]
Alphard
Profil
Ehm, $this->data určitě ne, staticky self::$data. Je mi jasné, že je to jen překlep, ale nevím, jestli to _fantomas dojde.
Také zdůrazňuji, že metoda Foo::init() se musí explicitně zavolat.

Vaše odpověď

Mohlo by se hodit


Prosím používejte diakritiku a interpunkci.

Ochrana proti spamu. Napište prosím číslo dvě-sta čtyřicet-sedm:

0