使用静态方法在php中设置常量条件

r3i60tvu  于 2023-03-11  发布在  PHP
关注(0)|答案(1)|浏览(101)

我尝试让IntegratedApp类常量使用配置文件中的值,然后在MakeConnectionController中使用该常量。但是IntegratedApp类中的常量PORTAL_BASE_URL_STAG在为其分配静态方法时出现**下划线错误(错误消息:常量表达式包含无效操作)**出现在常量上,有没有办法不用静态方法就给常量类赋变量?
代码示例:
配置文件:

[test]
stagingApiUrl = 'https://api-test-first.com/';

文件名:

namespace Project\Constants;

class IntegratedApp
{

    const PORTAL_BASE_URL_STAG = self::getUrl();

    public static function getUrl() {
        $base_url = $this->config->test->stagingApiUrl ? $this->config->test->stagingApiUrl : 'https://api-test-second.com/';

        return (string)$base_url;
    }

}

创建连接控制器. php文件:

use Project\Constants\IntegratedApp;

class MakeConnectionController extends BaseController
{
    $baseUrl = IntegratedApp::PORTAL_BASE_URL_STAG;
}
8fsztsew

8fsztsew1#

您可以使用以下解决方法(使用define()):

<?php
namespace Project\Constants;

define('PORTAL_BASE_URL_STAG',IntegratedApp::getUrl());

class IntegratedApp
{

    const PORTAL_BASE_URL_STAG = PORTAL_BASE_URL_STAG;

    public static function getUrl() {

        return (string)"Foo";
    }

}

print IntegratedApp::PORTAL_BASE_URL_STAG;//Foo
  • define()同一文件中类外部的常量
  • 使用静态方法获取值
  • 然后使用创建的常量设置类常量

希望你没有这么多的魔法,你应该修正$this的用法,因为在静态方法中你没有访问$this的权限。
不要问为什么这样做:-)它工作。看起来这里有一种晚期类常量绑定。

相关问题