PHP-致命错误:不在对象上下文中使用$this
我真的很抱歉问这个问题,因为我知道以前有人问过很多次,我也读过这些帖子,但我就是想不通 我有一门课:PHP-致命错误:不在对象上下文中使用$this,php,object,this,Php,Object,This,我真的很抱歉问这个问题,因为我知道以前有人问过很多次,我也读过这些帖子,但我就是想不通 我有一门课: class Fivehundredpx { private $_user; public $fivehundredpx; public function __construct(User $user){ $this->_user = $user->data(); $this->fivehundredpx = $user
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时,我得到一个致命错误:在不在对象上下文消息中时使用$this
但是,如果我在类中添加另一个方法:
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访问它
public function userData(){
print 'here is some text '. Fivehundredpx::fivehundredpx();
}
或者可以尝试:
public function userData(){
$obj = new Fivehundredpx();
print 'here is some text '. $obj->fivehundredpx();
}
根据您的评论,您无法访问以下用户的属性:
$user->data()->fivehundredpx;
而类用户的方法数据不返回对象。添加到方法数据:
return $this;
最后。请在实际调用fhpxEndpoint的地方发布代码。类用户的方法是否返回$this?@b4rt3kk您的意思是在构造函数中?如果不是,那么在实例化Fivehundredpx时,您应该首先传入一个User实例。现在在你打电话之前就应该是致命的fhpxEndpoint@tlenss是的,你是对的。Fivehundredpx对象实际上是在其他地方实例化的,并在用户实例中传递。我只是在更接近我使用实例的地方添加了它,但忘记了包含用户参数。Sorrydoing这意味着不再在这里打印一些文本jinky32并生成致命错误:调用未定义的方法Fivehundredpx::fivehundredpxI可以使用$user->data->Fivehundredpx访问该值;虽然如果我不能,那么我的userData方法肯定不会打印出值,因为$this->fivehundredpx是由$user->data->fivehundpx在构造函数中设置的,我只是用它来尝试和调试这个问题