简体   繁体   中英

How can I get the callable method in a Trait?

I have this trait:

<?php

namespace App\Traits;

trait PageConfigTrait {

    public function getFormAction()
    {
        return ""; // I want to return 'edit'
    }

}

and this controller using the Trait:

<?php

namespace App\Http\Controllers;

use App\Traits\PageConfigTrait;

class BillTypeController extends Controller
{
    use PageConfigTrait;

    public function index()
    {
     //
    }

    public function edit()
    {
        echo $this->getFormAction();
    }    
}

What I need to return 'edit' on getFormAction method on my Trait?

I'm using Laravel.

Thank you

You can do it by using PHP predefined constants.

<?php

namespace App\Traits;

trait PageConfigTrait {

    public function getFormAction($caller)
    {
        return $caller; 
    }

}

and then you can call it like this:

<?php

namespace App\Http\Controllers;

use App\Traits\PageConfigTrait;

class BillTypeController extends Controller
{
    use PageConfigTrait;

    public function index()
    {
     //
    }

    public function edit()
    {
        echo $this->getFormAction(__FUNCTION__);
    }    
}

If you don't want to pass anything around, you can use debug_backtrace(); to do something like this:

<?php

namespace App\Traits;

trait PageConfigTrait {

    public function getFormAction()
    {
        $trace = debug_backtrace();
        $caller = $trace[1];

        return $caller['function'];
    }

}

Then you can use it like you wanted in the code above.

Resource:https://www.php.net/manual/en/language.constants.predefined.php

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