简体   繁体   中英

can't calling a class methods in laravel controller class

Suppose I have this code:

class UserController extends Controller
{
    protected $test;

    public function __construct()
    {
        $this->test = new Test();

    }

    // first call this func
    public function add_name()
    {
        $this->test->add_name('name1')
        return $this->test->get_name();
    }

    // then this one
    public function show_name()
    {
        return $this->test->get_name();
    }

}

class Test
{
    protected  $name;

    public function get_name()
    {
        return $this->name;
    }

    public function add_name($name)
    {
        $this->name = $name;
    }
}

So when I call show_name() function after add_name() in UserController (first class), return nothing. What is my code problem? (when calling add_name() function it work correctly)

In Laravel, It's not good practice to write separate class inside the Controller file . You have to create a separate class file in app/Classes directory . say for eg your class, Class_Test.php inside app/class. And in Your Controller file, on the top, you need to include namespace of class . Your controller function should be like .

use App\\Classes\\Class_Test;

class UserController extends Controller {

 public function add_name() { //call the class function Class_Test::add_name('name1'); } // then this one public function show_name() { Class_Test::get_name(); } 

}

Hope this Help you .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM