0

メソッドの引数に基づいてプロパティを作成しようとしています。例えば:

class Test{

   public function newProperty($prop1,$prop2){

   //I want to create $this->argu1 and $this->argu2 after calling newProperty method. 

  }
}


$test=new Test();
$test->newProperty('argu1','argu2')

これは可能ですか?助けてくれてありがとう。

4

2 に答える 2

3

単純な:

$this->$prop1 = 'whatever';

未定義の数の引数を処理したい場合は、次を使用できます。

foreach(func_get_args() as $arg) {
  $this->$arg = 'some init value';
}

一方、これらのプロパティはすべて公開されるため、これはまったく不要です。

$test->argu1 = 'whatever';

まったく同じことをします。

于 2012-05-14T19:26:13.350 に答える
1

これを試して:

class Test{

    private argu1 = '';
    private argu2 = '';

    public function newProperty($argu1,$argu2){
        //This is a great place to check if the values supplied fit any rules.
        //If they are out of bounds, set a more appropriate value.

        $this->prop1 = $argu1;
        $this->prop2 = $argu2;

    }
}

クラスのプロパティに$propまたは$arguという名前を付ける必要があるかどうかという質問からは少しわかりません。後ろ向きになったら教えてください。

于 2012-05-14T19:27:04.800 に答える