0

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.

3
  • 4
    protected static $sizes = array('original' => ? Commented Dec 5, 2013 at 18:20
  • You're mixing instances and static functions. Don't. Either make both function and variable static or make none of them static. Commented Dec 5, 2013 at 18:21
  • Have you tried protected static $sizes ? Commented Dec 5, 2013 at 18:22

4 Answers 4

1

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];
  }
};
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.