【问题标题】:PHP - Fatal error: Using $this when not in object contextPHP - 致命错误:不在对象上下文中使用 $this
【发布时间】:2014-06-12 10:45:49
【问题描述】:

我真的很抱歉问这个问题,因为我知道这个问题已经被问过很多次了(而且我已经阅读了这些主题),但我无法解开这个问题。

我有一堂课:

class Fivehundredpx {
    private $_user;
    public $fivehundredpx;

    public function __construct(User $user){ 
        $this->_user = $user->data();
        $this->fivehundredpx = $user->data()->fivehundredpx;
    }

    public function fhpxEndpoint(){ //truncated - this function actually has a number of switch statements
        return $apistring = "https://api.500px.com/v1/photos?feature=user_favorites&username=". $this->fivehundredpx."&sort=rating&image_size=3&include_store=store_download&include_states=voted&consumer_key=I9CDYnaxrFxLTEvYxTmsDKZQlgStJG868GKb"; //this is the line that causes the error
    }

}

当 fhpxEndpoint() 被调用时,我得到了致命错误:Using $this when not in object context 消息。

但是,如果我在类中添加另一个方法:

public function userData(){
    print 'here is some text '. $this->fivehundredpx;
}

并从它打印出来的类之外调用它是一些文本 jinky32 正如预期的那样。

非常感谢任何帮助!

根据要求编辑: 方法是通过

调用的
$fivehundredpx = new Fivehundredpx;
$obj = $fivehundredpx->fhpxApiConnect($fivehundredpx->fhpxEndpoint());

fhpxApiConnect() 是:

public function fhpxApiConnect($apiString){
    print $apiString;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$apiString);
    curl_setopt($ch , CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
etc etc

像我在 fhpxApiConnect() 中所做的那样打印出 $apiString 表明该 url 已正确构建并且名称 jinky32 已正确插入,但我仍然收到致命错误

编辑: 好的,我已经玩过并找到了一种让它工作的方法。如果我将类变量更改为

public static $fivehundredpx;

然后设置它

public function __construct(User $user){
    self::$fivehundredpx=$user->data()->fivehundredpx;
}

然后我可以在 fhpxEndpoint() 中使用 self::$fivehundredpx 而不是 $this->fivehundredpx 访问它

【问题讨论】:

  • 请将代码贴在您实际调用 fhpxEndpoint() 的位置。
  • User 类的方法是否返回 $this?
  • @b4rt3kk 你的意思是在构造函数中吗?如果是这样,它不会
  • 在实例化Fivehundredpx 时,您应该首先传入一个用户实例。现在,即使在您致电 fhpxEndpoint 之前,它也应该是致命的
  • @tlens 是的,你是对的。 Fivehundredpx 对象实际上是在别处实例化的,并且确实传入了 User 的实例。我只是将它添加到更接近我使用实例的位置但忘记包含用户参数。对不起

标签: php object this


【解决方案1】:

试试这个:

public function userData(){
    print 'here is some text '. Fivehundredpx::fivehundredpx();
}

或者可以试试:

public function userData(){
    $obj = new Fivehundredpx();
    print 'here is some text '. $obj->fivehundredpx();
}

【讨论】:

  • 这样做意味着这里不再打印一些文本 jinky32 并生成致命错误:调用未定义的方法 Fivehundredpx::fivehundredpx()
【解决方案2】:

根据您的评论,您无法像这样访问 User 的属性:

$user->data()->fivehundredpx;

虽然 User 类的方法数据不返回您的对象。添加到方法数据:

return $this;

在最后。

【讨论】:

  • 我可以使用 $user->data()->fivehundredpx;尽管。如果我不能,那么我的 userData() 方法(我只是用来尝试和调试这个问题)肯定不会打印出该值,因为 $this->fivehundredpx 是由 $user->data( )->五百像素
猜你喜欢
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
相关资源
最近更新 更多