Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected type 'object'. Found 'void'.intelephense(1006) Issue in PHP MVC project

Getting Expected type 'object'. Found 'void'.intelephense(1006) Issue in PHP MVC project. I attached the relevant code and source that I followed (youtube) here. Appreciate it if someone can explain what happened.

Have a home controller with a function to get an instance of a model like this: (How I coded)

<?php

class Controller{

    public function model($model){

        require_once '../app/models/' . $model . '.php';
        
        return new $model();
    }
    
}

Have User.php class like this: (How I coded)

<?php 


class User{
    public $name;

    public function __construct()
    {
        
    }
}

Have Home controller like this: (How I coded)

<?php

class Home extends Controller{

    public function index($name = ''){

      
        $user = $this->model('User');
        $user->name = $name;
        echo $user->name;
        
    }

    public function test(){

        echo 'test_function()';

    }

    public function get_user_name(){

    }

    public function model($model){
        echo $model;
    }
}

Near the $user->name = $name; and the echo $user->name; it shows the error. this is the screenshot I'm afraid can't find the issue. I thought it was an issue with the model but was unable to resolve it yet. I am watching a youtube video series and doing this. this is the relevant video URL youtube video Coded as here but I'm in trouble. Can someone explain why this happen and where is the error, please? I want to clarify this MVC architecture.

like image 882
Terry Avatar asked Aug 31 '25 22:08

Terry


2 Answers

You can also define your variable by adding

 /**
 * 
 * @var object $user
 */

or maybe even

/**
 * 
 * @var User $user
 */

right before

 $user->name = $name;

That should make the error go away.

like image 75
Fata Sefer Avatar answered Sep 03 '25 14:09

Fata Sefer


This is because you override the method for getting model.

Just remove the last lines in your controller.

public function model($model){
    echo $model;
}

or modify like this (but this is not necessary because this contain main Controller)

public function model($model){
    var_dump(parent::model($model));
}

this part will call model method in your controller instead of parent controller where is defined right implementation

$user = $this->model('User'); // this probably echo output User
$user->name = $name; // this fail
like image 44
daremachine Avatar answered Sep 03 '25 15:09

daremachine