我正在尝试基于方法参数创建属性。例如:
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')
这可能吗?感谢您的任何帮助。
简单如下:
$this->$prop1 = 'whatever';
假设您要处理未定义数量的参数,则可以使用:
foreach(func_get_args() as $arg) {
$this->$arg = 'some init value';
}
另一方面,所有这些都是不必要的,因为所有这些属性都是公共的,因此:
$test->argu1 = 'whatever';
会做完全相同的事情。
试试这个:
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。 如果我把它们倒过来,请告诉我。