簡體   English   中英

如何在 Trait 中獲取可調用方法?

[英]How can I get the callable method in a Trait?

我有這個特點:

<?php

namespace App\Traits;

trait PageConfigTrait {

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

}

這個 controller 使用 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();
    }    
}

我需要在 Trait 的 getFormAction 方法上返回“編輯”什么?

我正在使用 Laravel。

謝謝

您可以使用 PHP 預定義常量來實現。

<?php

namespace App\Traits;

trait PageConfigTrait {

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

}

然后你可以這樣稱呼它:

<?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__);
    }    
}

如果你不想傳遞任何東西,你可以使用debug_backtrace(); 做這樣的事情:

<?php

namespace App\Traits;

trait PageConfigTrait {

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

        return $caller['function'];
    }

}

然后你可以在上面的代碼中像你想要的那樣使用它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM