8

I have a private function as written below in the Controller.

private function GetProjects($ProjectStatus) {
    return \App\Models\Project\Project_Model
            ::where('ProjectStatusID', $ProjectStatus)
            ->where('WhoCreatedTheProject', auth()->user()->UserID)->get();
}

Below is the action method that is using this private function.

public function ClientCancelledProjects() {
    $ProjectStatus = \App\Enumeration\Project\ProjectStatus::Cancelled;         
    $MyProjects = GetProjects($ProjectStatus);
    return view("Project.Client.MyProject", array("Projects" => $MyProjects));
}

Below is the Error coming when running the controller.

Call to undefined function App\Http\Controllers\Project\GetProjects()

Somebody knows why this is happening ? I am trying to reuse some lines of code as they are written many times in the Controller.

2 Answers2

27

To access functions in a controller from a function in the same controller, use self:::

public function ClientCancelledProjects() {
    $ProjectStatus = \App\Enumeration\Project\ProjectStatus::Cancelled;         
    $MyProjects = self::GetProjects($ProjectStatus);
    return view("Project.Client.MyProject", array("Projects" => $MyProjects));
}

Note: Self:: (uppercase) will work depending on the version of php installed, but for older versions, self:: is preferred.

Please check this link for more info: PHP - Self vs $this

Community
  • 1
  • 1
Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
10

Functions inside of a class are not global functions, and cannot be called that way. You need to use $this->GetProjects() instead.

aynber
  • 22,380
  • 8
  • 50
  • 63