如何从查询字符串初始化类属性?

时间:2013-08-31 15:50:57

标签: php

我想知道如何从查询字符串初始化类属性?我来了以下代码,我通过检查特定条件来检查和初始化类属性。

class Sample
{
    var $id;
    var $txtName;

    function Sample()
    {
        if(count($_REQUEST))
        {
            if(array_key_exists("id",$_REQUEST))
                $this->id = $_REQUEST['id'];
            if(array_key_exists("txtName",$_REQUEST))
                $this->txtName = $_REQUEST['txtName'];  
        }
    }

    //other functions
}

//--------------

$obj = new Sample();
$obj->getParam("id");
$obj->getParam("txtName");

是否有可能从某个基类扩展此Sample类并初始化类属性。为此,我有一些想法但不清楚的解决方案。就像下面的

class GetQueryStrings
{
    //something like child class can initialize their properties
}
class Sample extends GetQueryStrings
{
    var $id;
    var $txtName;

    function Sample()
    {
        if(count($_REQUEST))
        {
            if(array_key_exists("id",$_REQUEST))
                $this->id = $_REQUEST['id'];
            if(array_key_exists("txtName",$_REQUEST))
                $this->txtName = $_REQUEST['txtName'];  
        }
    }

    //other functions
}

//--------------

$obj = new Sample();
$obj->getParam("id");
$obj->getParam("txtName");

使用$obj->getParam("id");是否可以初始化$this->idSample而不在其构造函数中初始化它?

1 个答案:

答案 0 :(得分:1)

class GetQueryStrings
{
    public function __construct()
    {
        foreach ($_GET as $key => $val)
        {
            if (property_exists(get_class($this), $key))
                $this->$key = $val;
        }
    }
}

确保在覆盖构造函数时调用构造函数:

class Derived extends GetQueryString
{
    public function __construct()
    {
        parent::__construct();

        ... other code ...
    }
}