I'm currently studying OOP Method Chaining, but I'm having difficulties from making it work.
I've created setValue method where it returns a value based on the parameters.
Then, I've created setLabel method and added a parameter to be used after a setValue has been called.
Here is the current code I have:-
class Field
{
public $label;
public function setValue($property, $value)
{
$this->$property = new \stdClass();
$this->$property->value = $value;
$this->$property->label = $this->label;
return $this;
}
public function setLabel($label)
{
return $this->label = $label;
}
}
A sample code for retrieving the data:-
$field = new Field;
$field->setValue('textfield', 'something to print')->setLabel('Label here');
print $field->textfield->value; // Returns the value
print $field->textfield->label; // Returns an empty string
I can't figure out what's wrong with my code. Please help.
Assuming that the following is your goal:
print $field->textfield->value; // Returns the value
print $field->textfield->label; // Returns the label
if you want this to work:
$field = new Field;
$field->setValue('textfield', 'something to print')->setLabel('Label here');
Then you need to do something like this:
class FieldProperty {
public $label
public $value;
public setValue($value) { $this->value = $value; return $this; }
public setLabel($label) { $this->label = $label; return $this; }
}
class Field
{
public function setValue($property, $value)
{
$this->$property = new FieldProperty();
$this->$property->setValue($value);
return $this->$property;
}
}
Thinking about it further, we can add:
class Field
{
public function setValue($property, $value)
{
$this->$property = new FieldProperty();
$this->$property->setValue($value);
return $this->$property;
}
public function setProperty($propertyName)
{
$this->$propertyName = new FieldProperty;
return $this->$propertyName;
}
}
Now you can do this:
$field->setProperty('textfield')->setLabel('my label')->setValue('some value');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With