将数组关联并推入面向对象的变量 PHP

Associate and push an array into variable in object oriented PHP

我正在尝试将数组推送到 php7 中的变量中。我的代码是:

public $services = array(
    '01' => 'Canada Post - Priority',
    '02' => 'Canada Post - Regular Parcel',
    '03' => 'Canada Post - Xpresspost',
    '04' => 'Purolator Express 9AM',
    '05' => 'Purolator Express 1030AM',
    '06' => 'Purolator Express',
    '07' => 'Purolator Ground',
);

我希望推送以这种方式获得的数组,而不是硬代码部分

public function easypost_database()
    {

        \EasyPost\EasyPost::setApiKey('mykey');
        $cas = \EasyPost\CarrierAccount::all();
        $carriers = array();
        foreach($cas as $key=>$value) {
            $carriers[] = $value['type'];

       }

       return $carriers;
   }

我的数组 $carriers 看起来像这样;

Array ( [0] => CanadaPostAccount 
[1] => PurolatorAccount )

问题是当我将我的变量与我的数组相关联时,我的代码中断了。

public $services = $carriers;

public $services = $this->easypost_database();

不行。

你做的是行不通的,基本上是设计不好。

如果您需要在定义 easypost_database() 的 class 中使用 $carriers,您可能应该在创建此对象时注入此依赖项。

你会:

class MyClass {

   protected $services;

   public function __construct(array $services) {
     $this->services = $services;
   }
}

在不了解您的系统的更多信息的情况下,不可能猜测您如何解决您的依赖关系或者您是否使用任何类型的容器或服务定位器。但简单地说,要实例化此对象,您需要执行以下操作:

\EasyPost\EasyPost::setApiKey('mykey');
$cas = \EasyPost\CarrierAccount::all();
$carriers = [];
foreach($cas as $key=>$value) {
    $carriers[] = $value['type'];
}

$foo = new MyClass($carriers);

现在您可以从 class.

中访问 $this->services

但是属性定义需要能够在编译时解析,所以你想使用的那种表达式永远行不通。

来自manual

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.