我正在尝试编写我的对象成员,以便可以使用以下格式对其进行访问:
$object->member() // Returns current value of member
$object->member($new_value) // Sets value of member to $new_value
这是我的实现示例:
class Automobile
{
private $color;
private $make;
private $model;
public function __construct($inColor, $inMake, $inModel) {
$this->color($inColor);
$this->make($inMake);
$this->model($inModel);
}
private function gset($p, $v) {
if ($v) {
$this->{$p} = $v;
return $this;
} else {
return $this->{$p};
}
}
public function color($v = null) {
return $this->gset(__FUNCTION__, $v);
}
public function make($v = null) {
return $this->gset(__FUNCTION__, $v);
}
public function model($v = null) {
return $this->gset(__FUNCTION__, $v);
}
}
我正在寻找的效果是:
$car = new Automobile('Red', 'Honda', 'Civic');
var_dump($car->color()); // Returns Red
$car->color('Blue'); // Sets color to Blue
var_dump($car->color()); // Returns Blue
一切都按原样运行,但是我仍然希望能够从字面上传递null
给函数,以便它将null
作为值插入,但是由于参数的默认值null
也是,它将仅返回当前值:
$car->color(null); // Would like to insert null as car color, but this is obviously equivalent to $car->color()
var_dump($car->color()); // Returns Blue
无论如何,是否知道值是实际参数传递的结果还是使用默认值的结果?我认为我的第一个测试机会是在函数本身内部,到那时它已经被设置了。
关于如何实现我正在寻找的其他想法?
我意识到我可以null
为特定的成员(如)编写一个单独的函数$car->null_color()
,但此刻我正试图以某种方式将其压缩为相同的$object->member()
格式。
使用func_num_args()
以确定是否有任何参数通过与否。
function color($c = null) {
if(func_num_args() == 1) {
$this->color = $c;
}
return $this->color;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句