【问题标题】:Variables in Trait特征中的变量
【发布时间】:2019-10-28 19:15:12
【问题描述】:

我在 Laravel 中创建了一个 trait。

在 myconstruct 中,我调用了一个 setting('value') - 这是由 qcod/laravel-app-settings 包提供的。

但在我的方法中,当我引用 $this->token 或 $this->org_id 时,它会返回 NULL

我知道这些值已设置,因为它们在配置中显示并且也在数据库中正确设置。

我的 PHP 代码是:

<?php

namespace App\Traits;

use Illuminate\Support\Facades\Log;

trait PropertyBaseTrait
{

    private $org_id;
    private $token;
    private $is_set;

    public function __construct()
    {
        $this->org_id = setting('propertybase_org');
        $this->token = setting('propertybase_token');
    }

    public function base_url($method)
    {
        return 'https://pb-integrations-api-staging.herokuapp.com/api/v1/'.$method.'/'.$this->org_id.'';
    }

    public function post_lead($data)
    {
        $lead_data = array(
            'first_name'        => '',
            'last_name'         => '',
            'email'             => '',
            'phone1'            => '',
            'phone2'            => '',
            'phone3'            => '',
            'address'           => '',
            'city'              => '',
            'state'             => '',
            'zip_code'          => '',
            'country_name'      => '',
            'landing_page'      => '',
            'search_term'       => '',
            'referral_source'   => ''
        );

        $object_type = 'lead';
        $action_type = 'create';

        dd($this->token);

        $endpoint = $this->base_url('messages');

        $this->post_data( $endpoint, $object_type, $action_type, json_encode($data));
    }

【问题讨论】:

    标签: php laravel traits


    【解决方案1】:

    避免在特征中编写构造函数。这就是我能说的。

    相反,您可以将它们作为普通方法,然后在您的类构造函数中调用它。

    特质

    trait Bar
    {
        public function init()
        {
            $this->org_id = setting('propertybase_org');
            $this->token = setting('propertybase_token');
        }
    }
    

    class Foo
    {
        use Bar;
    
        public function __construct()
        {
            $this->init();
        }
    }
    

    【讨论】:

      【解决方案2】:

      问题是你在你的特质中,也许在你正在使用这个特质的班级中。 可能的情况:

      class MyClass {
          use MyTraitWithConstructor;
      
          public function __construct(){
              ...
          }
      }
      

      在这种情况下,特征构造函数不起作用。

      你能做什么?

      您可以像这样重命名特征构造函数:

      class MyClass {
      
          use PropertyBaseTrait {
              PropertyBaseTrait::__construct as private __prConstruct;
          }
      
          public function __construct(){
              $this->__prConstruct();
              ...
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-10-02
        • 1970-01-01
        • 1970-01-01
        • 2020-02-02
        • 2022-10-13
        • 2014-02-27
        • 2016-01-24
        • 2018-06-01
        • 2015-02-01
        相关资源
        最近更新 更多