Search code examples
phpmysqlormphpactiverecord

Passing variables to a has_one relationship in PhpActiveRecord


I'm using phpactiverecord (http://www.phpactiverecord.org/) in a project.

I have the below relationship definded. Is there anyway to pass a variable to it so I can change language_id on the fly?

static $has_one = array(
  array(
    'language', 
    'class_name' => 'Pages_lang', 
    'conditions' => array('language_id=1')
  )
);

I looked on the docs and it appears you can do:

static $has_one = array(
  array('language', 
    'class_name' => 
    'Pages_lang', 
    'conditions' => array('language_id=?','1'))
);

But passing a variable in:

static $has_one = array(
  array('language', 
    'class_name' => 
    'Pages_lang', 
    'conditions' => array('language_id=?',$language_id))
);

throws an error.

Im not really sure where I am going wrong.


Solution

  • static variables only make sense in the context of objects. They come into existance before an object of that type is actually created (instantiated).

    I'm not totally sure what you're trying to achieve here, but you most probably want to change the variable at some point in your program's control flow. In order to do that, you must either create and call a method within the class that sets the value of that static variable (advisable, see example code below) or set it explicitly from your main code (not advisable, also requires your variable to be public)

    class Foo
    {
        static $has_one = 'initial value';
    
        public static function setHasOne($value) {
            self::$has_one=$value;
        }
    }
    
    // main code:
    Foo::setHasOne('new value');
    

    For the sake of simplicity I've used a string variable here, but it works just the same with arrays.