douchengfei3985 2017-04-30 18:06
浏览 75
已采纳

Symfony教程中的PHP语法

Trying to get up to speed with Symfony, going thru the tutorial, and on this page (symfony.com/doc/current/forms.html) is the following sample:

$form = $this->createFormBuilder($task)
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->add('save', SubmitType::class, array('label' => 'Create Post'))
    ->getForm();

    return $this->render('default/new.html.twig', array(
        'form' => $form->createView(),
    ));

Having never seen this syntax before, I quickly ruled out call-chaining which it superficially appears to be, then found that interpreting each of the "bare" arrows as pointing to methods of $form was mostly correct. It ended up working correctly in this version:

$formBuilder = $this->createFormBuilder($task);
$formBuilder->add('task', TextType::class);
$formBuilder->add('dueDate', DateType::class);
$formBuilder->add('save', SubmitType::class, array('label' => 'Create Post'));
$form = $formBuilder->getForm();

    return $this->render('default/new.html.twig', array(
        'form' => $form->createView(),
    ));

So I'm trying to understand the original sample. If the correct interpretation of the seemingly disconnected arrows is "call method of the object named on the first line", this explains all except the line "->getForm();". If the same rule is applied to that line, however, that line becomes "$formBuilder->getForm();", which of course fails on the render() line because of the lack of assignment to $form (I mean, it still would have failed even if I'd kept the name $form for the builder).

So is there a mistake in the tutorial, or what subtleties of syntax am I missing?

I've searched extensively with combinations of ("php", "arrow", "syntax", ...) but haven't found anything about omitting the object name in a series of method calls.

  • 写回答

2条回答 默认 最新

  • douqi1625 2017-04-30 18:13
    关注

    This is in fact method chaining. The new lines between separate method calls is only for better code readability.

    This:

    $formBuilder = $this->createFormBuilder($task);
    $formBuilder->add('task', TextType::class);
    

    Is equivalent to this:

    $formBuilder = $this->createFormBuilder($task)
    ->add('task', TextType::class);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块