I've inherited a bit of code that is used to integrate with a third party (Highrise CRM). I'm a bit rusty on this side of PHP, so was looking for some help.
I want to assign a session variable within a class. At the moment I have the following code:
var $highrise_url = 'https://exam开发者_高级运维ple.highrisehq.com';
var $api_token = 'foofoofoofoofoofoofoofoo';
var $task_assignee_user_id = 'foofoo';
But I want the URL, token and ID to be set based on the session valuables I pull from the database of the user who is logged in i.e.
$_SESSION['hrurl']
$_SESSION['hrapi']
$_SESSION['hrid']
The class uses the variables set above in functions like:
$curl = curl_init($this->highrise_url.'/deals.xml');
I know that I CAN'T set a variable in a class like this:
var $highrise_url = $_SESSION['hrurl'];
So how do I do it?
I believe it's done by using the construct function, but I'm shaky at best, so would appreciate help :o)
Many thanks,
Gregor
Sounds like a job for the constructor:
class A
{
public $highrise_url;
public $api_token;
public $task_assignee_user_id;
public function __construct()
{
$this->highrise_url = $_SESSION['hrurl'];
$this->api_token = $_SESSION['hrapi'];
$this->task_assignee_user_id = $_SESSION['hrid'];
}
}
$a = new A();
A better solution may be to pass the values to the constructor:
public function __construct($highrise_url, $api_token, $task_assignee_user_id)
{
$this->highrise_url = $highrise_url;
$this->api_token = $api_token;
$this->task_assignee_user_id = $task_assignee_user_id;
}
...
$a = new A($_SESSION['hrurl'], $_SESSION['hrapi'], $_SESSION['hrid']);
The second way cuts down on coupling between your class and the $_SESSION
array. That way you can use (or test) the class without relying on session functionality.
Set it in the constructor:
class HighriseClass {
var $highrise_url;
function __construct() {
$this->highrise_url = $_SESSION['hrurl'];
}
}
精彩评论