Reputation: 327
I'm trying to write my object members so they can be accessed with the format:
$object->member() // Returns current value of member
$object->member($new_value) // Sets value of member to $new_value
Here's an example of my implementation:
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);
}
}
The effect I'm looking for is:
$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
Everything works great as is, HOWEVER I'd like to also be able to literally pass null
to the function so it will insert null
as the value, but since the default of the parameter is null
also it will only return the current value:
$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
Is there anyway to know if a value is the result of the actual parameter being passed or the result of using the default value? I think my first opportunity to test is inside the function itself, and by then it's already set either way.
Any other thoughts on how to achieve what I'm looking for?
I realize I can write a separate function to null
a particular member, such as $car->null_color()
, but at the moment I'm trying to squeeze it somehow into the same $object->member()
format.
Upvotes: 2
Views: 737
Reputation: 1202
Use func_num_args()
to determine if any arguments passed or not.
function color($c = null) {
if(func_num_args() === 1) {
$this->color = $c;
}
return $this->color;
}
Upvotes: 1
Reputation: 5520
Is this what you're looking for?
public function color($v = null) {
//If nothing or NULL is sent to this function
//return current color
if ($v === null) return $this->color;
//Set color
$this->color = $v;
}
Upvotes: 0