0

I have a class like below:

$structure = new stdClass();

$structure->template->view_data->method       = 'get_sth';
$structure->template->view_data->lang         = $lang;
$structure->template->view_data->id_page      = $id_page;
$structure->template->view_data->media_type   = 'ibs';
$structure->template->view_data->limit        = '0';
$structure->template->view_data->result_type  = 'result';

And I am curious about if it can be written like below?

$structure->template->view_data->method       = 'get_sth_else',
                               ->lang         = $lang,
                               ->id_page      = $id_page,
                               ->media_type   = 'ibs',
                               ->limit        = '0',
                               ->result_type  = 'result',

                    ->another-data->method    = 'sth_else',
                                  ->type      = 'sth',
                                  ->different = 'sth sth';
vascowhite
  • 18,120
  • 9
  • 61
  • 77
  • 2
    You can't use your syntax, but you can return `$this` in each setter in order to call `setA($a) -> setB($b) -> ... -> setZ($z)`. – moonwave99 Oct 08 '12 at 09:09
  • They could make it easier by overloading the __call function to overload the set* functions. – Shane Oct 08 '12 at 09:11

2 Answers2

1

No, you have to pass each time the object and the value:

$structure->template->view_data->method       = 'get_sth_else';
$structure->template->view_data->lang         = $lang;
$structure->template->view_data->id_page      = $id_page;
$structure->template->view_data->media_type   = 'ibs';
$structure->template->view_data->limit        = '0';
$structure->template->view_data->result_type  = 'result';

$structure->template->another_data->method    = 'sth_else';
$structure->template->another_data->type      = 'sth';
$structure->template->another_data->different = 'sth sth';
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
0

What you are talking about is called a 'Fluent Interface', and it can make your code easier to read.

It can't be used 'out of the box', you have to set up your classes to use it. Basically, any method that you want to use in a fluent interface must return an instance of itself. So you could do something like:-

class structure
{
    private $attribute;
    private $anotherAttribute;

    public function setAttribute($attribute)
    {
        $this->attribute = $attribute;
        return $this;
    }

    public function setAnotherAttribute($anotherAttribute)
    {
        $this->anotherAttribute = $anotherAttribute;
        return $this;
    }

    public function getAttribute()
    {
        return $this->attribute;
    }

    //More methods .....
}

and then call it like this:-

$structure = new structure();
$structure->setAttribute('one')->setAnotherAttribute('two');

Obviously, this will not work for getters, as they must return the value you are looking for.

vascowhite
  • 18,120
  • 9
  • 61
  • 77