Skip to content
Advertisement

Initialize model in controller constructor

I searched for this error many times on google with no solutions, only what I see that if it’s a static function I must use self:: and not $this-> but if it’s not static I can use $this-> I know that, but when I run the PHP file(in terminal I run: php test.php) to test adding a new employee this error appears:

PHP Fatal error: Uncaught Error: Using $this when not in object context in /var/www/localdomain/phpAssignment/app/services/employees.php:37

private $EmployeeModel;

public function __construct()
{
    $this->EmployeeModel = new EmployeeModel();
}
// Add Employee
public function add($data)
{
    if ($this->EmployeeModel->addEmployee($data)) {    // the error with this line
        echo "employee added";
    }
}

Also, I used this type of initialization that I will get from an extended controller class and i get the same error

public function __construct(){
      $this->userModel = $this->model('EmployeeModel');
    }

When I make a new model in the function directly it works fine as

{
    $EmployeeModel = new EmployeeModel();
    if ($EmployeeModel->addEmployee($data)) {
        echo "employee added";
    }
}

test.php contains this:

$employeeData = [
    'name' => 'John',
    'manager_id' => 2
    ];
employees::add($employeeData);

I want to make it reusable not to add it in every function

Advertisement

Answer

First of all you should use $this inside the class body. This will solve your Fatal error. Second, for using model methods inside controller you should implement external class (model) and then you can use model’s methods via referencing ->, cause it’s an object.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement