Laravel 5.1: Calling a function from string

2019-07-10 02:38发布

问题:

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