Laravel 5.1: Calling a function from string

懵懂的女人 提交于 2019-12-24 00:54:50

问题


Currently I'm trying to call a function from a string.

This is the function, that I'll call later:

<?php
namespace App\Validation\Options;

class FacebookOptionValidation
{
    static public function validate()
    {
       echo: 'example';
       die();
    }
}

Here is my controller:

<?php
namespace App\Http\Controllers\Profile;

use App\Validation\Options;

class ProfileUserEditController extends Controller {

    public function updateUserOption()
    {
        $class = 'Options\FacebookOptionValidation';

        $class::validate();
    }
}

In this case Laravel shows an error: Class 'Options\FacebookOptionValidation' not found

But when I call my function like this, everything works fine:

use App\Validation\Options;

class ProfileUserEditController extends Controller {

    public function updateUserOption()
    {
        Options\FacebookOptionValidation::validate();
    }
}

As mentioned here, it's possible to call a class/function from a string. But in my case it's not possible - neither in the static or non-static variant.

Is that a 'laravel-thing'?


回答1:


Try call with full namespace

    class ProfileUserEditController extends Controller {

        public function updateUserOption()
        {
            $class = 'App\Validation\Options\FacebookOptionValidation';

            $class::validate();


         }
}



回答2:


With PHP7 you can even do this:

(App\Validation\Options\FacebookOptionValidation::class)::validate();

One line of code and without using a string



来源:https://stackoverflow.com/questions/34789209/laravel-5-1-calling-a-function-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!