Charlestone
Charlestone

Reputation: 1260

How to directly use class name as a static attribute in PHP

I have a class name and I want to use the name to get static attributes from the class. Of course I don't want to have to write the class name again and again. All I could come with is this.

class MyClass
{
    public static $shopClass = 'super\Long\Class\name\I\want\to\have\only\Here';

    public function do($classesStaticAttribute){

        $shopClass = self::$shopClass; //I would like to avoid this row...
        $this->doSomeStuff($shopClass::$$classesStaticAttribute);

    }
}

Is there any way I could avoid the $shopClass = self::$shopClass row and access the attribute directly? {self::$shopClass}::$$classesStaticAttribute does not work.

Upvotes: 0

Views: 56

Answers (1)

Phil
Phil

Reputation: 164762

You could simply import the class symbol via use, ie

use super\Long\Class\name\I\want\to\have\only\Here as Shop;

class MyClass
{
    public function do($classesStaticAttribute){

        $this->doSomeStuff(Shop::$$classesStaticAttribute);

    }
}

Alternatively, say you want the $shopClass property to be settable externally, you can simply use

$this->doSomeStuff(constant(self::$shopClass . '::$' . $classesStaticAttribute));

See http://php.net/manual/function.constant.php

Upvotes: 2

Related Questions