在面向对象的PHP中将数组关联并推送到变量中

I'm trying to push an array into a variable in php7. My code is:

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',
);

Instead of the harded code part I wish to push my array that I've obtain in this way

public function easypost_database()
    {

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

       }

       return $carriers;
   }

My array $carriers looks like that;

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

The problem is that when I associate my variable with my array my code breaks.

public $services = $carriers;

and

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

won't work.

doutao6380
doutao6380 您可以返回运营商。您无法使用动态值定义属性。
2 年多之前 回复
dongxi3859
dongxi3859 返回$运营商在其他地方使用它
2 年多之前 回复
dqy27359
dqy27359 $this->service[]=$value['type'],是的。对面你的意思是什么?
2 年多之前 回复
dongli7236
dongli7236 为什么我不能这样做呢?
2 年多之前 回复
dsnnvpobaljihv3490
dsnnvpobaljihv3490 所以,而不是$carrier[]==$value['type'];我应该使用$this->service==$value['type'];然后将我的变量服务声明为public$services;?
2 年多之前 回复
doudun2565
doudun2565 你不能以这种方式初始化类属性。为什么不在你的函数中使用$this->services?
2 年多之前 回复

1个回答

What you are doing wont work, and it is basically poorly designed.

If you need to use $carriers inside the class where you define easypost_database(), you should probably inject this dependency when creating this object.

You'd have:

class MyClass {

   protected $services;

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

Without knowing more about your system it's not possible to guess how are you resolving your dependencies or if you are using any type of container or service locator. But putting it simply, to instantiate this object you'd need to do something like:

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

$foo = new MyClass($carriers);

And now you'd be able to access $this->services from within your class.

But properties definition need to be able to be resolved at compile time, so the kind of expression you want to use would never work.

From the 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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐