在构造中设置私有变量不起作用

时间:2017-01-02 04:27:54

标签: php function class variables static

这是我的工作代码: -

public static function getOperatingSys() {

    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    $osPlatform = "Unknown OS";

    $osArray = array(
        '/windows nt 10/i'     =>  'Windows 10',
        '/windows nt 6.3/i'     =>  'Windows 8.1',
        '/windows nt 6.2/i'     =>  'Windows 8'
        );

    foreach ($osArray as $regex => $value) { 

        if (preg_match($regex, $user_agent)) {
            $osPlatform = $value;
        }

    }   

    return $osPlatform;
}

正如您所看到的,$user_agent = $_SERVER['HTTP_USER_AGENT'];正在发挥作用。

但是,如何将其转换为此?:

private $user_agent;

    public function __construct() {
        $this->user_agent = $_SERVER['HTTP_USER_AGENT'];
    }

    public static function getOperatingSys() {

        $osPlatform = "Unknown OS";

        $osArray = array(
            '/windows nt 10/i'     =>  'Windows 10',
            '/windows nt 6.3/i'     =>  'Windows 8.1',
            '/windows nt 6.2/i'     =>  'Windows 8'
            );

        foreach ($osArray as $regex => $value) { 

            if (preg_match($regex, $user_agent)) {
                $osPlatform = $value;
            }

        }   

        return $osPlatform;
    }

我正在使用private $user_agent,但我怎样才能使它等于$_SERVER['HTTP_USER_AGENT'];然后如何使用它/在我的函数getOperatingSys()中调用它?

1 个答案:

答案 0 :(得分:2)

您需要更改的第一件事是让getOperatingSys不再是静态函数。第二件事就是使用$ this->引用user_agent时。像下面这样的东西应该有效:

private $user_agent;

public function __construct() {
    $this->user_agent = $_SERVER['HTTP_USER_AGENT'];
}

public function getOperatingSys() {

    $osPlatform = "Unknown OS";

    $osArray = array(
        '/windows nt 10/i'     =>  'Windows 10',
        '/windows nt 6.3/i'     =>  'Windows 8.1',
        '/windows nt 6.2/i'     =>  'Windows 8'
        );

    foreach ($osArray as $regex => $value) { 

        if (preg_match($regex, $this->$user_agent)) {
            $osPlatform = $value;
        }

    }   

    return $osPlatform;
}