PHP类获取全局变量

时间:2014-04-10 07:55:13

标签: php twitter

我正在使用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

}

请帮助。

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:0)

一个类是一个独立的,可重复使用的便携式代码单元 因此,它永远不应该在任何情况下依赖 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

无论如何,这就是我要做的。顺便说一句:请检查并尝试坚持coding standards


更新:
事实证明你已经有了一个构造函数。很好,只需将其改为:

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);
}