dte29947
2016-06-08 23:48
浏览 264
已采纳

无法在laravel控制器类中调用类方法

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)

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • duanfan5012 2016-06-09 04:10
    最佳回答

    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 .
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题