【问题标题】:Using $this inside static methods and methods called by this method在静态方法和此方法调用的方法中使用 $this
【发布时间】:2012-12-05 11:17:07
【问题描述】:

如何在从静态方法调用的方法中使用$this->var1? 我有这个方法:

static public function getModuleConfigInputfields(array $data) {
    $fields = new InputfieldWrapper();
    $modules = Wire::getFuel('modules');
    $field = $modules->get("InputfieldText");
    $field->attr('name+id', 'apiKey');
    $field->attr('value', $data['apiKey']);
    $field->label = "API Key (Developer Key)";
    $field->description = 'Enter the API key';
    $fields->append($field);
    $field = $modules->get("InputfieldSelect");
    $field->attr('name+id', 'list_id');
    $mailing_lists = self::get_mc_lists();
    foreach($mailing_lists['data'] as $list)
    {
        $field->addOption($list->list_name, $list->list_id); 
    }
    $field->label = "Mailing list";
    $field->description = 'Choose a mailing list';
    $fields->append($field);
    return $fields;
}

我想调用这个方法:

public function get_mc_lists()
{
    $api = new MCAPI($this->apiKey);

    $retval = $api->lists();

    if ($api->errorCode){
        return array('errorcode' => $api->errorCode, 'errormessage' => $api->errorMessage);
    } else {
        return array('data' => $retval['data'], 'total' => $retval['total']);
    }

}

但我收到此错误:

不在对象上下文中使用 $this 时出错(第 31 行

第 31 行,即:$api = new MCAPI($this->apiKey);

那么我该如何解决这个问题,解决这个问题......我真的被困在这个问题上

提前致谢!

【问题讨论】:

  • 燃油似乎充满静电、气味!

标签: php static


【解决方案1】:

静态方法没有与之关联的任何对象,因此在静态方法中没有可用的$this 引用。但是,您可以将变量声明为静态并直接使用它而无需 $this 引用。

【讨论】:

    【解决方案2】:

    Trimbitas 是正确的,你需要

    self::$apiKey
    

    $this 仅适用于实例化对象,不适用于静态类函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多