0

クエリ文字列からクラス プロパティを初期化する方法を教えてください。特定の条件をチェックしてクラス プロパティをチェックおよび初期化する次のコードが付属しています。

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

4

1 に答える 1

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 ...
    }
}
于 2013-08-31T16:26:42.637 に答える