如何将控制器的私有属性用作静态属性?

How to use private property of controller as static property?

所以,这个问题几乎解释了我想要什么。这是我正在做的最少代码。

class AuthorizeController extends Controller
{
    private $aNetEnvironment;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->aNetEnvironment = env('ANetEnvironment');
    }

    public function setEnvironment()
    {
        $controller = new AnetController\GetCustomerProfileController($request);
        // $this->aNetEnvironment = SANDBOX
        $response = $controller->executeWithApiResponse( 
            \net\authorize\api\constants\ANetEnvironment::$this->aNetEnvironment 
        ); 
    }
}

搜索 Whosebug 我有两个选项,都试过了都没有运气。

尝试,{$this->aNetEnvironment} 给出

syntax error, unexpected ')', expecting '('

尝试,$$this->aNetEnvironment 给出

Object of class App\Http\Controllers\AuthorizeController could not be converted to string

编辑:

尝试,${$this->aNetEnvironment} 给出

Access to undeclared static property: net\authorize\api\constants\ANetEnvironment::$SANDBOX

还有其他选择吗?

您可以利用 PHP 的 constant() helper。来自文档:

Signature:

constant ( string $name ) : mixed

Return the value of the constant indicated by name.

constant() is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function.

This function works also with class constants.

所以在你的情况下:

$response = $controller->executeWithApiResponse( 
    constant('\net\authorize\api\constants\ANetEnvironment::' . $this->aNetEnvironment) 
); 

要以这种方式将 class 属性用作 variable variables,您需要从 $ 开始并将 属性 包装在 {} 中,例如${$this->property} 所以你应该能够在你的控制器中使用以下内容:

\net\authorize\api\constants\ANetEnvironment::${$this->aNetEnvironment}