user1238763
user1238763

Reputation: 5

get class variable in static method

I have a class variable that I need to have available without an instance of the class. Something like

$size = Image::getSize('original');

Here's my attempt, but it getSize returns null.

class Image extends Model {

    protected $sizes =
    ['original'=>['w'=>'2048','h'=>'1536','f'=>'1'],
        'originalSquare'=>['w'=>'2048','h'=>'1536','f'=>'1'],
        'thumb'=>['w'=>'120','h'=>'120','f'=>'1'],
        'overview'=>['w'=>'554','h'=>'415','f'=>'3'],
        'category'=>['w'=>'260','h'=>'195','f'=>'2'],
        'medium'=>['w'=>'554','h'=>'415','f'=>'1']];

    public static function getSize($size)
    {

        return(self::$sizes[$size]);
    }
}

Is there a better way to accomplish this? $sizes is also used internally by an instance of this class.

Upvotes: 0

Views: 75

Answers (4)

what is sleep
what is sleep

Reputation: 905

Static functions cannot access instance fields or methods.

If $size is a instance member, you can not get it through a static function. This makes sense if you think about it.

Upvotes: 0

Cyclonecode
Cyclonecode

Reputation: 30001

You will need to declare $size as static inside your class:

class Image extends Model {
  protected static $sizes = array(
    'original' => array('w' => '2048', 'h' => '1536', 'f' => '1') 
  );

  public static function getSize($size) {
     return self::$sizes[$size];
  }
};

Upvotes: 1

Shimu
Shimu

Reputation: 1147

You have to use protected static (!!) $sizes[...] because without the static you can't access this property within a static function afaik. And if you want to access it you have to use $this instead of self.
But you still can access the static property within the class.

Upvotes: 0

Dan
Dan

Reputation: 2109

you want to have it be a static variable to unbind it from needing a class instance.

Upvotes: 0

Related Questions