J
J
jazzus2018-12-24 08:27:09
Laravel
jazzus, 2018-12-24 08:27:09

How to pass method name to variable in Laravel?

I need to transfer the name of the method with brackets to a variable. And I don't know how to write it. Tried 'method()' and other password guessing - no luck.
Statuses in the Model

//Опубликован
  public function active()
  {
      return 1;
  }

  //Не опубликован
  public function inactive()
  {
      return 2;
  }

  //Проверка 
  public function isActive()
  {
      if ($this->status_id==$this->active()) return true;
      return false;
  }
  //Обновление статуса
  public function statusUpdate($status)
  {
      $this->update(['status_id'=>$this->$status]);
  }

I need to transfer the name of the method from the controllers to statusUpdate($status) to the $status variable. How to do it? I tried to write differently in the controller, for example
$product->statusUpdate('active()');
it does not work

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2018-12-24
@jazzus

What kind of horror are you doing?
Okay, in the forehead it will be like this:

//Обновление статуса
public function statusUpdate($status)
{
    $this->update(['status_id'=>$this->{$status}()]);
}

$product->statusUpdate('active');

Okay, like this:
class Foo
{
    public const ACTIVE  = 1;
    public const INACTIVE  = 2;
    
    public function isActive()
    {
        return $this->status_id === static::ACTIVE;
    }

    public function statusUpdate($status)
    {
        $this->update(['status_id' => $status]);
    }
}

(new Foo)->statusUpdate(Foo::ACTIVE);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question