0

我有一个像下面这样的课程:

$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';

我很好奇它是否可以像下面这样写?

$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';
4

2 回答 2

1

不,您必须每次传递对象和值:

$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';
于 2012-10-08T09:11:04.077 回答
0

您所说的称为“流畅的界面”,它可以使您的代码更易于阅读。

它不能“开箱即用”,您必须设置类才能使用它。基本上,您想在流畅接口中使用的任何方法都必须返回其自身的实例。所以你可以做类似的事情: -

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 .....
}

然后这样称呼它:-

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

显然,这对 getter 不起作用,因为它们必须返回您正在寻找的值。

于 2012-10-08T09:32:40.743 回答