【发布时间】: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 的实例。我只是将它添加到更接近我使用实例的位置但忘记包含用户参数。对不起