我正在尝试基于方法参数创建属性。例如:
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。请让我知道我是否将它们倒退。