dozug64282 2018-04-18 13:59
浏览 64
已采纳

在面向对象的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.

  • 写回答

1条回答 默认 最新

  • duanhai4046 2018-04-18 14:38
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 tensorrt 推理 yolov8框出现错误
  • ¥15 用hc 05,做蓝牙控制小车 小车只能说初始遥控方向影响,后续不能更改
  • ¥15 51单片机怎么把每次输入键值保存到数组作为我的确认键的判断条件呢
  • ¥15 c语言字符串单词入门问题报错
  • ¥30 我现在是双非人工智能专业不知道要不要转到软件工程专业
  • ¥15 请问12脉波整流机组的外特性曲线具体是如何推导
  • ¥15 abaqus里的python算法
  • ¥100 如何在思科模拟器中进入CEF模式
  • ¥15 Simulink 仿真如何使用MATLAB function模块获取到仿真过程中某一仿真时刻输入到模块的函数的值?
  • ¥50 关于#微信小程序#的问题:微信小程序支持h5实现webrtc h264 h265低延迟传输渲染,能付费帮我们解决一下吗