PhP 构造函数和链接

PhP constructor and chaining

最近查看了SwiftMailer包,发现了这个无法解释的问题:

// #1
$message = new Swift_Message($subject)->setFrom($f)->setTo($t)->setBody($body);

// #2
$message = new Swift_Message($subject);
$message->setFrom($f)->setTo($t)->setBody($body);

// #3
$message = new Swift_Message($subject);
$message->setFrom($f);
$message->setTo($t);
$message->setBody($body);

变体 #1 来自 SwiftMailer 文档,它不起作用,它给出了 "unexpected '>'" 解析错误。这个问题很容易解决,变体 #2 和 #3 工作得很好。

我认为方法链接是 PHP 中广泛使用的技术,而且我还认为 #1 是完全有效的。为什么它没有按预期工作?

我的PHP是V7.1.1

谢谢,阿敏。

第一个示例在文档中没有这样写,class 实例化的示例方法链的 none 因为它从未有效 PHP.

文档是这样写的:

// Create the message
$message = (new Swift_Message())

    // Give the message a subject
    ->setSubject('Your subject')

    // Set the From address with an associative array
    ->setFrom(['john@doe.com' => 'John Doe'])

    // Set the To addresses with an associative array (setTo/setCc/setBcc)
    ->setTo(['receiver@domain.org', 'other@domain.org' => 'A name'])

    // Give it a body
    ->setBody('Here is the message itself')

    // And optionally an alternative body
    ->addPart('<q>Here is the message itself</q>', 'text/html')

    // Optionally add any attachments
    ->attach(Swift_Attachment::fromPath('my-document.pdf'));

请注意 class 是在括号内实例化的。这允许直接从构造函数链接方法。