passing variable to a php class
I am a beginner in php. and trying to work with Oauth. but this is not the point. the point is following: I have an Oauth class, there are four functions which return urls like this:
class tOauth{
......
function accessTokenURL() {
return 'http://api.twitter.com/oauth/access_token';
}
function authenticateURL() {
return 'http://api.twitter.com/oauth/authenticate';
}
......
}
this works fine. but now I want these functions to be generic, such that they are suitable for any social sites. this means I have to danymically pass all urls and return them at run time. so I come up something like this:
class tOauth{
....
public $accessTokenURL,$authenticateURL;
function accessTokenURL() {
return $this->accessTokenURL;
}
function authenticateURL() {
return $this->authenticateURL;
}
....
}
and at run time I call them like this:
$oauth=new Oauth(key,secret);
$oauth->accessTokenURL='http://www.facebook.com/oauth/access_token';
$oauth->authenticateURL='http://www.facebook.com/oauth/authenticate';
$token=$oauth->requestToken($someurl);
but for some reason, this doesn't see开发者_高级运维ms to work. I did not change anything else. it seems I can not daynamically assign variables like this. does any body know what may be the problem? thanks for any tips.
Update: whole sample code can be find here: https://github.com/abraham/twitteroauth/blob/master/twitteroauth/twitteroauth.php
Why not write getter and setter methods for your class variables?
You already have methods, that return accessTokenURL and authentificateURL.
I believe this might work:
class tOauth{
....
public $accessTokenURL,$authenticateURL;
function accessTokenURL() {
return $this->accessTokenURL;
}
function authenticateURL() {
return $this->authenticateURL;
}
function set_accessTokenURL($token)
{
$this->accessTokenURL = $token;
}
function set_authenticateTokenURL($token)
{
$this->authenticateTokenURL = $token;
}
....
}
Update: Your code does not show any details about requestToken()
method. The following solution gets you access token instead.
You read something you did not set according to your code. Replace the last line with
$token=$oauth->accessToken($someurl);
and it will work for accessToken
.
Also consider inheritance that will allow you to store common instructions in tOauth
class and the service-specific ones in separate classes inheriting from it (eg. Twitter_Oauth
may inherit from your tOauth
class and have specific URLs set to default from the beginning, without the need to set them every time).
精彩评论