如何将方法参数传递给类属性?

时间:2012-05-14 19:23:31

标签: php oop function

我正在尝试基于方法参数创建属性。例如:

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')

这可能吗?感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

简单如下:

$this->$prop1 = 'whatever';

假设您想要处理未定义数量的参数,可以使用:

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

另一方面,所有这些都是非常不必要的,因为所有这些属性都是 public ,因此:

$test->argu1 = 'whatever';

会做同样的事情。

答案 1 :(得分: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,我对这个问题有点不清楚。如果我让他们倒退,请告诉我。