ATK4: Error: Using $this when not in object context

109 Views Asked by At

I am defining a method in ATK4 with an expression field in it:

$this->addExpression('answered')->set(function($model,$select){
    return $select->dsql()
          ->table('answer')
          ->field($select->expr('if(count(*)>0,"Y","") as answered'))
          ->where('usecollection_id',$select->getField('id'))
          ->where('student_id',$this->api->auth->get('id'));

  })->type('boolean')->caption('Besvaret');

It works fine on my development machine, but on the production server it throws a fatal error: PHP Fatal error: Using $this when not in object context in file.php

This is the problematic line:

$this->api->auth->get('id')

Any idea what causes this difference and how to make it work?

2

There are 2 best solutions below

2
On BEST ANSWER

One way is to pass $this to enclosed function like this:

$self = $this;
$this->addExpression('answered')->set(function($model,$select)use($self){
    echo $self->api->auth->get('id');
});

That's how you should pass variables quite often to anonymous functions in PHP.

Another possibility in this particular case is to simply use $select->api->..., $model->api->... or any other ATK4 object instead of this->api->.... That's because all ATK4 objects have reference to API class, so $whateverObject->api->... will always work and always point to same API class object.

0
On

You're referencing a variable ($this) that is not passed nor declared within the function (you're passing $model and $select to the function).

I'm not smart enough to tell you the best way to fix this, maybe you can define $auth_id (set it to $this->api->auth->get('id')) before the function is called and pass that variable to it as well?

There is bound to be a better way though...