Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Method Chaining setting and getting a value

Tags:

oop

php

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.

like image 244
Catherine Salvador Avatar asked Nov 08 '22 10:11

Catherine Salvador


1 Answers

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');
like image 105
ryantxr Avatar answered Nov 15 '22 06:11

ryantxr