帮助浏览器检测代码

时间:2011-09-10 15:07:06

标签: php

我对此代码的第36行有疑问。

<?PHP
class Browser
{
    private $props    = array("Version" => "0.0.0",
                                "Name" => "unknown",
                                "Agent" => "unknown") ;

    public function __Construct()
    {
        $browsers = array("firefox", "msie", "opera", "chrome", "safari",
                            "mozilla", "seamonkey",    "konqueror", "netscape",
                            "gecko", "navigator", "mosaic", "lynx", "amaya",
                            "omniweb", "avant", "camino", "flock", "aol");

        $this->Agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        foreach($browsers as $browser)
        {
            if (preg_match("#($browser)[/ ]?([0-9.]*)#", $this->Agent, $match))
            {
                $this->Name = $match[1] ;
                $this->Version = $match[2] ;
                break ;
            }
        }
    }

    public function __Get($name)
    {
        if (!array_key_exists($name, $this->props))
        {
            die "No such property or function $name" ;
        }
        return $this->props[$name] ;
    }

    public function __Set($name, $val)
    {
        if (!array_key_exists($name, $this->props))
        {
            SimpleError("No such property or function.", "Failed to set $name", $this->props) ;
            die ;
        }
        $this->props[$name] = $val ;
    }

}

?> 

这是错误die "No such property or function $name" ;的行,任何帮助都会被占用。

2 个答案:

答案 0 :(得分:2)

这条线必须是这样的,而不是:

die("No such property or function $name");

有关详细信息,请参阅here

答案 1 :(得分:1)

为什么不将该代码重写为此?:

<?php

class Browser
{

    public $Version = "0.0.0";
    public $Name = "unknown";
    public $Agent = "unknown";

    public function __Construct()
    {
        $browsers = array("firefox", "msie", "opera", "chrome", "safari",
                            "mozilla", "seamonkey",    "konqueror", "netscape",
                            "gecko", "navigator", "mosaic", "lynx", "amaya",
                            "omniweb", "avant", "camino", "flock", "aol");

        $this->Agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        foreach($browsers as $browser)
        {
            if (preg_match("#($browser)[/ ]?([0-9.]*)#", $this->Agent, $match))
            {
                $this->Name = $match[1] ;
                $this->Version = $match[2] ;
                break ;
            }
        }
    }
}

?>

无论如何,我建议您使用一些已有的库来检测浏览器,例如http://chrisschuld.com/projects/browser-php-detecting-a-users-browser-from-php/