Laravel 5.1: Calling a function from string

2019-07-10 02:29发布

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'?

2条回答
Rolldiameter
2楼-- · 2019-07-10 02:51

With PHP7 you can even do this:

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

One line of code and without using a string

查看更多
爷的心禁止访问
3楼-- · 2019-07-10 02:59

Try call with full namespace

    class ProfileUserEditController extends Controller {

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

            $class::validate();


         }
}
查看更多
登录 后发表回答