我正在使用https://github.com/seaofclouds/tweet
我想通过index.php?consumer_key=xxx
。在通过这个之后,我想进入PHP类,但我遇到了错误。
这是下面的代码。完整代码:http://pastebin.com/gCzxrhu4
//$consumer_key = $_GET['consumer_key'];
class ezTweet {
private $consumer_key = $consumer_key; // getting error
private $consumer_key = 'xxxxx'; // working
private $consumer_secret = 'xxxx';
//other things
}
请帮忙。
类是一个独立的、可重用的、可移植的代码单元
因此,在任何情况下,它都不应该依赖GLOBAL变量来初始化其属性或完成其工作。
如果您需要一个类访问一个值,请通过构造函数或setter方法将该值传递给该类:
class EzTweet
{//class names start with UpperCase, and the { goes on the next line
private $consumer_key = null;//initialize to default, null
public function __construct($cKey = null)
{//pass value here, but default to null -> optional
$this->consumer_key = $cKey;//set value
}
public function setConsumerKey($cKey)
{
$this->consumer_key = $cKey;//set value later on through setter
return $this;
}
}
//use:
$ezTwitter = new EzTwitter();
if (isset($_GET['consumer_key']))
$ezTwitter->SetConsumerKey($_GET['consumer_key']);//set value
不管怎样,我都会这么做。BTW:请检查并尽量遵守编码标准。
更新:
事实证明你已经有了一个构造函数。好吧,只是把它改成:
public function __construct($cKey = null)//add argument
{
$this->consumer_key = $cKey;//add this
// Initialize paths and etc.
$this->pathify($this->cache_dir);
$this->pathify($this->lib);
$this->message = '';
// Set server-side debug params
if ($this->debug === true)
error_reporting(-1);
else
error_reporting(0);
}
您不能用$变量设置属性类的值,在这种情况下,您需要在构造类之前设置。
class ezTweet
{
private $consumer_key = '';
private $consumer_secret = 'xxxx';
public function __construct($consumer_key)
{
if (!is_string($consumer_key) || !strlen(trim($consumer_key))) {
throw new 'InvalidArgumentException('"consumer_key" cannot be empty!');
}
$this->consumer_key = $consumer_key;
}
public function getConsumerKey()
{
return $this->consumer_key;
}
}
$consumer_key = (isset($_GET['consumer_key']) ? $_GET['consumer_key'] : null);
try {
$ezTweet = new ezTweet($consumer_key);
// [...]
}
catch ('InvalidArgumentException $InvalidArgumentException) {
echo $InvalidArgumentException->getMessage();
}