初始化/将类成员变量分配给其他类成员变量


Initializing/Assigning class member variables to other class member variables

我正在回到Web开发并以正确的方式重新学习PHP,我遇到了一个非常愚蠢的问题,我应该能够解决,但不能。

我正在尝试基本上将基本 url 值分配为类属性,然后使用该值分配给新的类属性。

class Endpoints {
   protected $baseURL = 'https://api.com';
   protected $baseAccountsURL = $this->baseURL . '/accounts';
}

我尝试直接访问$baseURL,没有$this>,但它也失败了。我更喜欢使用 CONST,但将 CONST 分配给其他 CONST 的功能在 5.6 之前不可用。 我已经查看了PHP类属性页面,并搜索了SO,但我来自Java背景,所以我在这里的问题可能是术语。和语法:p

提前感谢!

你不能以这种方式分配属性,你需要在构造函数中执行此操作:

class Endpoints {
   protected $baseURL = 'https://api.com';
   protected $baseAccountsURL;
   public function __construct()
   {
       $this->baseAccountsURL = $this->baseURL . '/accounts';
   }
}

或者,这将起作用:

class Endpoints {
   protected $baseURL = 'https://api.com';
   protected $baseAccountsURL = 'https://api.com/accounts';
}

但我认为第一个选择是你需要的。