Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
using class variables
  • hey!

    I'm trying to use variables in a model, but not having much luck.  Here is basically what I have:

    class Model_Currency extends \Model_Crud
    {
    private static $country = 'GBP'; 

    public static function get_currency_code(){
    $code = DB::query('SELECT currencyCode FROM currency_code WHERE countryCode = "' . $self::country . '" LIMIT 1')->execute();
    $code = $code->as_array();

    return $code[0]['currencyCode'];
    }
    }

    But I get an error: Undefined class constant 'country' referring to the get_currency_code function.
    I tried non-statically too with non-static variable and refer to it in the function as $this->country, but get error: Using $this when not in object context

    I also tried sticking the variable in an init function - like you would a constructor, but that didn't work either!


  • itcanitcan
    Accepted Answer
    it should be: self::$country
  • HarroHarro
    Accepted Answer
    Even better:

    static::$country

    And I would advise against declaring something as private, unless you have a very good reason to do so. Use protected instead.
  • thanks for your help, guys. OK, so now I have:

    protected $country = 'GBP';

    and am referring to it as: static::$country

    but I get an error: Access to undeclared static property: Model_Currency::$country
  • DOH! nevermind... I realised I didn't have 'static' declared for the variable! 

    Thanks very much for your help
  • OK, so I'm now trying to wrap the variable and a setter function in an _init method:

    public static function _init(){
    static $country = '';
    static::get_country();
    }

    public static function get_country(){ 
     static::$country = 'GBP'; 
    }

    I get error: Access to undeclared static property: Model_Currency::$country

    Also, when I try to access the variable without the get_country function call (like:

    public static function _init(){
    static $country = 'GBP';
    }

      static::$country (but this is in the function as before)
     
    I get: 

    Access to undeclared static property: Model_Currency::$country
  • it's OK... I figure out that the variable should be declared outside the init!

    Thanks anyway! 

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion