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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog